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