Passing self.var (instance attribute) as default m

2019-01-28 23:01发布

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

标签: python class
1条回答
SAY GOODBYE
2楼-- · 2019-01-28 23:46

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
    ...
查看更多
登录 后发表回答