实例属性作为默认参数

2024-06-16 11:40:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python3,我对kwargs有一个小问题。是否可以使用实例属性作为默认参数值?我的意思是这样的:

class foo:
    def __init__(self, a,b):
        self.a = a
        self.b = b

    def setNewA(self, a=self.a):
        print(a)

但我有个错误:

^{pr2}$

如果我使用类名,我有:

AttributeError: type object 'foo' has no attribute 'a'

我知道另一种方法是使用这样的方法:

    def setNewA(self, a=None):
        a = a or self.a
        print(a)

但也许有什么办法?在


Tags: 实例方法self属性fooinitdef错误