Search code examples
pythonclassoopinstanceself

Is it impossible to pass a instance variable as default of a method keyword?


This will not work:

class myClass:

    def __init__(self, name):
        self.name = name

    def methodA(self, name=self.name):
        print(f"Hello {name}!")

myInstance = myClass("Frank")

Because:

NameError: name 'self' is not defined

Questions

  1. Why is that? Is self.name not already defined at the initialization of the class?
  2. Is there a way to have name defined at initialization of a class instance while also being able to changing its value when calling specific methods at the same time? I don't want to always change its value with a separate line (e.g. like so: myInstance.name = "Peter") before I call a method. And, I also don't want to be forced to pass it on using a keyword (e.g. like so: def methodB(self, name=name_typed_when_calling_method) every time I call a method that uses that variable.

Solution

  • self is not defined when the default argument is evaluated, which is when the method is defined. It's just a function parameter, which gets bound to an argument when the method is called.

    What you need to do is use a sentinel (like None) as the default, and check for that inside the body of the method where self is defined.

    class myClass:
    
        def __init__(self, name):
            self.name = name
    
        def methodA(self, name=None):
            if name is None:
                name = self.name
            print(f"Hello {name}!")
    
    myInstance = myClass("Frank")