Python类变量在__init__中不可见?

10 投票
4 回答
11260 浏览
提问于 2025-04-15 12:37

这段代码出现了一个错误提示,我觉得很意外:

class Foo(object):
    custom = 1
    def __init__(self, custom=Foo.custom):
        self._custom = custom

x = Foo()

有没有人能给我解释一下?

4 个回答

3

类的内容在类本身被定义之前就会执行,所以默认参数的值不能引用这个类。只要把 custom 设为默认值(不带类的前缀)就可以了。

7

我们采取的做法是这样的:

class Foo( object ):
    custom = 1
    def __init__( self, arg=None )
        self._custom = self.custom if arg is None else arg

这样就避免了一个让人困惑的问题,那就是名字 Foo 是否已经被定义过。

16

这里的Foo是看不见的,因为你正在构建它。不过,由于你和custom在同一个范围内,所以你可以直接使用custom,而不是Foo.custom

class Foo(object):
    custom = 1
    def __init__(self, mycustom=custom):
        self._custom = mycustom

但是要注意,之后如果你改变了Foo.custom的值,这不会影响到后面创建的Foo看到的custom的值:

class Foo(object):
    custom = 1
    def __init__(self, mycustom=custom):
        self._custom = mycustom

one = Foo()
Foo.custom = 2
two = Foo()
print (two._custom)  # Prints 1

如果你改用一个特殊的默认值,就可以实现你想要的效果:

class Foo(object):
    custom = 1
    def __init__(self, mycustom=None):
        if mycustom is None:
            self._custom = Foo.custom
        else:
            self._custom = mycustom

one = Foo()
Foo.custom = 2
two = Foo()
print (two._custom)  # Prints 2

撰写回答