如何在python中动态创建类变量
我需要创建一堆类变量,我想通过循环遍历这样的列表来完成它:
vars = ('tx', 'ty', 'tz') # plus plenty more
class Foo():
for v in vars:
setattr(no_idea_what_should_go_here, v, 0)
可能吗?我不想将它们作为实例(在 __init__
中使用 self
),而是作为类变量。
I need to make a bunch of class variables and I would like to do it by looping through a list like that:
vars = ('tx', 'ty', 'tz') # plus plenty more
class Foo():
for v in vars:
setattr(no_idea_what_should_go_here, v, 0)
is it possible? I don't want to make them for an instance (using self
in the __init__
) but as class variables.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您可以在创建类后立即运行插入代码:
此外,您可以在创建类时动态存储变量:
You can run the insertion code immediately after a class is created:
Also, you can dynamically store the variable while the class is being created:
使用
type
类构造函数!Use the
type
class constructor!如果出于任何原因您不能使用雷蒙德在类创建后设置它们的答案,那么也许您可以使用元类:
If for any reason you can't use Raymond's answer of setting them up after the class creation then perhaps you could use a metaclass:
setattr(对象、名称、值)
这个是
getattr()
的对应项。参数是一个对象、一个字符串和一个任意值。该字符串可以命名现有属性或新属性。如果对象允许,该函数会将值分配给属性。例如,这些是等效的:
setattr(object, name, value)
This is the counterpart of
getattr()
. The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it.For example, these are equivalent:
locals()
版本在课堂上对我不起作用。以下可用于动态创建类的属性:
The
locals()
version did not work for me in a class.The following can be used to dynamically create the attributes of the class:
您需要的函数是:
setattr(obj, name, value)
这允许您为给定类设置命名属性(可以是
self
)。此函数的内置文档非常不言自明:
示例使用
此功能的一种用途是使用字典来设置多个类属性,在我的例子中,这是来自 xpath 定义。我觉得通过将可能更脆弱的 xpath 定义全部保留在一个地方,可以提高可维护性:
The function you need is:
setattr(obj, name, value)
This allows you to set named attributes for a given class (this can be
self
).The built in documentation for this function is pretty self-explanatory:
Example use
One use of this is to use a dictionary to set multiple class attributes, in my case this was from xpath definitions. I felt this improved maintainability by keeping potentially more fragile xpath definitions all in one place:
您可以使用“foo”创建全局变量。 (或您的班级名称)位于名称的开头:
You can create global variables with "foo." (or the name of your class) at the beggining of the name: