[英]How to add attribute to class before __init__?
Question 题
I have a Python module that creates instances of many other modules at runtime. 我有一个Python模块,可在运行时创建许多其他模块的实例。 The other modules are specified via an external configuration file, which also houses all arguments/values for each module's
__init__
. 其他模块通过外部配置文件指定,该文件还包含每个模块
__init__
所有参数/值。
I would like to add the same attribute to all new instances, but I don't want to add a new arg to __init__
on all of my classes. 我想为所有新实例添加相同的属性,但是我不想在所有类上都向
__init__
添加新的arg。 How can I go about this? 我该怎么办?
My Thoughts 我的想法
One possible solution: on the fly, I can add a new arg to __init__
by somehow manipulating the __init__
attribute on the module. 一种可能的解决方案:在运行中,我可以通过某种方式操纵模块上的
__init__
属性来向__init__
添加一个新的arg。 Then I can pass it the attribute I want to add on all instances. 然后,我可以将要在所有实例上添加的属性传递给它。
I am pretty sure this violates the Zen of Python. 我很确定这违反了Python的Zen。 That being said, I am curious how one could do this?
话虽这么说,我很好奇一个人该怎么做?
You could iterate over the **kwargs
__init__
parameter and use __setattr__
to automatically set any new passed parameter. 您可以遍历
**kwargs
__init__
参数,并使用__setattr__
自动设置任何新传递的参数。 Example: 例:
class Foo:
def __init__(self, **kwargs):
for key in kwargs:
self.__setattr__(key, kwargs[key])
You would only have to blindly add these two lines plus the **kwargs argument to your classes, then: 您只需将这两行以及** kwargs参数盲目添加到您的类中,然后:
f = Foo(name="bar")
print(f.name)
Output: 输出:
bar
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.