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
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 class Foo
yet, it wouldn't be a Foo
instance!) You can't refer to the class by name inside the definition either; referring to Foo
would also cause a NameError
: 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:
def fiz(self, num1=None):
if num1 is None:
num1 = self.val1
...