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
self.name
not already defined at the initialization of the class?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.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")