This question already has an answer here:
While assigning num1 = self.var1
in function fiz
, Python says unresolved reference. Why is that?
class Foo:
def __init__(self):
self.var1 = "xyz"
def fiz(self, num1=self.var1):
return
Method (and function) default parameter values are resolved when the method is defined. This leads to a common Python gotcha when those values are mutable: "Least Astonishment" and the Mutable Default Argument
In your case, there is no
self
available when the method is defined (and if there was such a name in scope, as you haven't actually finished defining the classFoo
yet, it wouldn't be aFoo
instance!) You can't refer to the class by name inside the definition either; referring toFoo
would also cause aNameError
: Can I use a class attribute as a default value for an instance method?Instead, the common approach is to use
None
as a placeholder, then assign the default value inside the method body: