-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
DanielBell99
  • 896
  • 5
  • 25
  • 57

3 Answers3

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)
Stijn B
  • 350
  • 2
  • 12
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.

brunns
  • 2,689
  • 1
  • 13
  • 24
  • To further the explanation; this is because inside of `process()` `self.` needs a local declaration of `self.`, which as you've shown should be passed. – DanielBell99 Mar 02 '22 at 12:38
-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.

DanielBell99
  • 896
  • 5
  • 25
  • 57