Python -使用类字段作为__init__ [duplicate]中关键字参数的值

fkvaft9z  于 2023-03-28  发布在  Python
关注(0)|答案(1)|浏览(131)

此问题在此处已有答案

How can I avoid issues caused by Python's early-bound default parameters (e.g. mutable default arguments "remembering" old data)?(10个答案)
Why does a class' body get executed at definition time?(3个答案)
5年前关闭。
__init__中,有没有一种很酷的Python方法可以使用类字段(类变量)作为关键字参数的可变默认值?
下面是一个例子:

class Foo():

    field = 5

    def __init__(self, arg=field): # arg=Foo.field => name 'Foo' is not defined
        self.arg = arg

# ok, let's start
obj_1 = Foo()
print(obj_1.arg) # 5, cool

# then I want to change Foo.field
Foo.field = 10
print(Foo.field) # 10, obviously
obj_2 = Foo()
print(obj_2.arg) # still 5, that's sad :(

为什么会这样呢?
我知道我可以这样做:

class Qux():

    field = 5

    def __init__(self, arg='default'): 
        self.arg = {True:Qux.field, False:arg}[arg == 'default']

Qux.field= 10
obj_3 = Qux()
print(obj_3.arg) # 10

但有没有更简单的方法呢?
先谢了。

igetnqfo

igetnqfo1#

只需将参数设置为None。然后测试参数是否为__init__中的None。如果是,则将其设置为默认值:

class Foo():
    field = 5
    def __init__(self, arg=None):
        if arg is None:
            self.arg = Foo.field
        else:
            self.arg = arg

上述逻辑也可以浓缩为:

self.arg = Foo.field if arg is None else arg

相关问题