Python:创建对象并向其添加属性 [英] Python: create object and add attributes to it
问题描述
我想在Python中创建一个动态对象(在另一个对象内部),然后向其中添加属性。
我试过:
obj = someobject
obj.a = object()
setattr(obj.a,'somefield','somevalue')
但这不起作用。
我设置的属性从<$> c $ c> for 循环遍历值列表,例如
params = attr1','attr2','attr3']
obj = someobject
obj.a = object()
for p in params:
obj.ap#其中p来自for循环变量
在上面的例子中,我会得到 obj .a.attr1
, obj.a.attr2
, obj.a.attr3
。
我使用了 setattr
函数,因为我不知道如何做 obj。 $
如何设置基于属性的属性上面的例子中 p
的价值?
使用我古老的 Bunch 食谱,但如果你不想做一个束类,一个非常简单的一个已经存在于Python - 所有函数可以有任意属性(包括lambda函数)。所以,以下工作:
obj = someobject
obj.a = lambda:None
setattr obj.a,'somefield','somevalue')
Bunch
食谱是OK的,是一个风格决定我当然会留给你。
I want to create a dynamic object (inside another object) in Python and then add attributes to it.
I tried:
obj = someobject
obj.a = object()
setattr(obj.a, 'somefield', 'somevalue')
but this didn't work.
Any ideas?
edit:
I am setting the attributes from a for
loop which loops through a list of values, e.g.
params = ['attr1', 'attr2', 'attr3']
obj = someobject
obj.a = object()
for p in params:
obj.a.p # where p comes from for loop variable
In the above example I would get obj.a.attr1
, obj.a.attr2
, obj.a.attr3
.
I used the setattr
function because I didn't know how to do obj.a.NAME
from a for
loop.
How would I set the attribute based on the value of p
in the example above?
You could use my ancient Bunch recipe, but if you don't want to make a "bunch class", a very simple one already exists in Python -- all functions can have arbitrary attributes (including lambda functions). So, the following works:
obj = someobject
obj.a = lambda: None
setattr(obj.a, 'somefield', 'somevalue')
Whether the loss of clarity compared to the venerable Bunch
recipe is OK, is a style decision I will of course leave up to you.
这篇关于Python:创建对象并向其添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!