-3

I quite often come across this object-oriented programming problem in Python, where I always seem to have both of these approaches fail. I have extensive experience with OOP in other languages, but only now using this in Python.

I want to call-upon a declared variable from __init__(self).

What is/ should be the standard approach?


Invoking self.foo:

class MyClass:
    def __init__(self):
        self.foo = 'value'

    def process():
        print(self.foo)  # !

test = MyClass()

Traceback:

NameError: name 'self' is not defined

Invoking foo:

class MyClass:
    def __init__(self):
        self.foo = 'value'  # `self.` kept here

    def process():
        print(foo)  # !

test = MyClass()

Traceback:

NameError: name 'foo' is not defined
1

3 Answers 3

2

You need to pass the self argument in every method (when defined in the class) :

class MyClass:
    def __init__(self):
        self.foo = 'value'

    def process():
        print(self.foo)  # `self` is not defined,
                         # you need to give it as argument

Corrected code:

class MyClass:
    def __init__(self):
        self.foo = 'value'

    def process(self):
        print(self.foo)
Sign up to request clarification or add additional context in comments.

Comments

1

Neither - you want:

class MyClass:
    def __init__(self):
        self.foo = 'value'

    def process(self):
        print(self.foo)  # !

test = MyClass()
test.process()

All methods need self as an argument.

1 Comment

To further the explanation; this is because inside of process() self.<var> needs a local declaration of self., which as you've shown should be passed.
-1

Someone had posted a comment stating:

def process(self)

Where self. needed to be added to the class method which uses any self. var/ obj.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.