Suppose we have the dummy class below:
class Foo:
def __init__(self, x):
self.x = x
def bar(value=self.x):
print(value)
And suppose we created an instance of our class and tried to call the bar
method without passing an argument:
foo_1 = Foo(5)
foo_1.bar()
The execution of the second line above generates a NameError
, claiming that name 'self' is not defined
. Why can we not set an instance attribute to a default value in a method? Of course, we can set a different default value, such as a None
value, and manually check for the presence of this default value:
class Foo:
def __init__(self, x):
self.x = x
def bar(value=None):
if not(value):
print(self.x)
else:
print(value)
Can someone offer an explanation?