且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将类变量作为默认值分配给类方法参数

更新时间:2023-02-11 20:08:36

你的理解有误.self 本身就是该函数定义的一个参数,因此它不可能在此时的作用域内.它只在函数本身的范围内.

Your understanding is wrong. self is itself a parameter to that function definition, so there's no way it can be in scope at that point. It's only in scope within the function itself.

答案只是将参数默认为None,然后在方法内部检查:

The answer is simply to default the argument to None, and then check for that inside the method:

def doSomething(self, a=None):
    if a is None:
        a = self.z
    self.z = 3
    self.b = a