Skip to content Skip to sidebar Skip to footer

Passing Self.var (instance Attribute) As Default Method Parameter

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, nu

Solution 1:

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
    ...

Post a Comment for "Passing Self.var (instance Attribute) As Default Method Parameter"