0

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
LateGameLank
  • 113
  • 5
  • 2
    _"Of course, we can set a different default value, such as a `None` value"_ - yes, do that. See also https://stackoverflow.com/q/1132941/3001761 for _when_ the default value gets evaluated. – jonrsharpe Jul 17 '23 at 15:01
  • 1
    See [PEP 661](https://peps.python.org/pep-0661/) for a proposed solution to defining custom sentinel values should `None` be a valid argument. (Also, use a specific check, instead of assuming that your sentinel is the only falsey value that might be passed: `if value is not None` instead of `if not value:`.) – chepner Jul 17 '23 at 15:13

0 Answers0