在 Python 中,我可以在运行时更改类的结构吗?

I_d*_*hon 0 python monkeypatching

在 Python 中,您可以像这样在运行时将新的实例变量添加到类的实例中...

>> class Foo:
>>     def __init__(self, bar):
>>         self.bar = bar
>> 
>> f = Foo()
>> setattr(f, "baz", "spam")
>> f.baz
"spam"
Run Code Online (Sandbox Code Playgroud)

...但它只对 instance 有影响,f对 class 没有影响foo

>> x = Foo()
>> x.baz
AttributeError: 'Foo' object has no attribute 'baz'
Run Code Online (Sandbox Code Playgroud)

有没有办法将新的实例变量添加baz到类中Foo,以便该类的所有新实例都具有新变量?

小智 5

您可以设置类的属性而不是实例。

setattr(Foo, "baz", "spam")
Run Code Online (Sandbox Code Playgroud)

输出

>>> class Foo:
...     def __init__(self, bar):
...         self.bar = bar

>>> f = Foo('bar')
>>> setattr(Foo, "baz", "spam")
>>> f.baz
'spam'
>>> f2 = Foo('bar')
>>> f2.baz
'spam'
Run Code Online (Sandbox Code Playgroud)