[英]Can you add attributes to an object dynamically?
I would like to create an object then add attributes to the object on the fly. 我想创建一个对象,然后动态地向对象添加属性。 Here's some pseudocode EX1: 这是一些伪代码EX1:
a = object()
a.attr1 = 123
a.attr2 = '123'
a.attr3 = [1,2,3]
EX2: the first page of this PDF EX2: 此PDF的第一页
In Python is it possible to add attributes to an object on the fly (similar to the two examples I gave)? 在Python中,可以动态地向对象添加属性(类似于我给出的两个示例)? If yes, how? 如果有,怎么样?
If you are using Python 3.3+, use types.SimpleNamespace : 如果您使用的是Python 3.3+,请使用types.SimpleNamespace :
>>> import types
>>> a = types.SimpleNamespace()
>>> a.attr1 = 123
>>> a.attr2 = '123'
>>> a.attr3 = [1,2,3]
>>> a.attr1
123
>>> a.attr2
'123'
>>> a.attr3
[1, 2, 3]
In Python is it possible to add attributes to an object on the fly (similar to the two examples I gave)? 在Python中,可以动态地向对象添加属性(类似于我给出的两个示例)?
Yes. 是。
If yes, how? 如果有,怎么样?
You could do: 你可以这样做:
class AttrHolder:
pass
a = AttrHolder()
a.attr1 = 123
a.attr2 = '123'
a.attr3 = [1,2,3]
Or even something truly awful like: 甚至是一些非常糟糕的东西:
import email #my choice of module is arbitrary
email.random_attribute = 'hello'
The unasked question: should you be doing this? 未提出的问题:你应该这样做吗? Probably not. 可能不是。 You're just using these things as stand-ins for a proper dict
. 你只是使用这些东西作为正确的dict
替身。 If you want named attributes, consider a namedtuple
. 如果需要命名属性,请考虑使用namedtuple
。
A = namedtuple('Attribute_Holder',['attr1','attr2','attr3'])
a = A(123,'123',[1,2,3])
This provides a (loose) contract for A
, and gives a nice repr
: 这为A
提供了(松散)合约,并给出了一个很好的repr
:
In [70]: print(a)
Attribute_Holder(attr1=123, attr2='123', attr3=[1, 2, 3])
Or just use a dict
. 或者只是使用一个dict
。 That's what they're for. 这就是他们的目的。
In fact, that's what you're doing when you 'add attributes on the fly', just with an unnecessary layer of abstraction. 实际上,当你“动态添加属性”时,这就是你正在做的事情,只需要一个不必要的抽象层。 Consider, using the above AttrHolder
: 考虑一下,使用上面的AttrHolder
:
In [77]: a = AttrHolder()
In [78]: a.__dict__
Out[78]: {}
In [79]: a.hi = 'hello'
In [80]: a.__dict__
Out[80]: {'hi': 'hello'}
You're using a dict
whether you like it or not! 无论你喜欢与否,你都在使用dict
!
Here is an example: 这是一个例子:
class Test:
pass
for mark, name in enumerate(("attr1", "attr2", "attr3")):
setattr(Test, name, mark)
print Test.attr1
print Test.attr2
print Test.attr3
output: 输出:
0
1
2
So, the answer is "yes". 所以,答案是肯定的。 Although it might not be such a good idea (could lead to problems such as losing track of the attributes or something). 虽然它可能不是一个好主意(可能导致诸如失去属性或某些东西的问题)。
Um, am I missing something? 嗯,我错过了什么吗? Take the following example: 请看以下示例:
class C():
def __init__(self, x):
self.myX = x
c = C(42)
c.attr1 = 123
print c.myX
print c.attr1
What seems to be the problem? 什么似乎是问题?
I use dictionaries for the exact purpose that you are describing (at least from my understanding of the question)... 我使用词典的目的与你描述的完全相同(至少从我对这个问题的理解)......
dict = {}
dict["attr1"] = 123
dict["attr2"] = '123'
dict["attr3"] = [1,2,3]
dict.get("attr1")
If you really want to add attributes to an anonymous instances of an anonymous class , you could write: 如果你真的想要为匿名类的匿名实例添加属性,你可以写:
>>> obj = type('obj', (), {})()
>>> obj.attr1 = 123
>>> obj.attr2 = '123'
>>> obj.attr3 = [1,2,3]
But, really, don't do this! 但是,真的,不要这样做!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.