且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建对象并向其添加属性?

更新时间:2023-11-05 09:32:10

你可以使用我古老的 Bunch 食谱,但如果你不想制作bunch class",一个非常简单的Python 中已经存在——所有函数都可以具有任意属性(包括 lambda 函数).因此,以下工作:

obj = 某个对象obj.a = lambda: 无setattr(obj.a, 'somefield', 'somevalue')

与古老的Bunch 配方相比,清晰度的降低是否还可以,这是我当然会留给您的风格决定.

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.