的Python:创建对象和属性添加到它 [英] Python: create object and add attributes to it

查看:230
本文介绍了的Python:创建对象和属性添加到它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在Python中创建一个动态对象(另一个对象中),然后添加属性给它。

I want to create a dynamic object (inside another object) in Python and then add attributes to it.

我试过:

obj = someobject
obj.a = object()
setattr(obj.a, 'somefield', 'somevalue')

但这并没有工作。

but this didn't work.

任何想法?

编辑:

我设置从循环它通过值列表,例如

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

在上面的例子中我会得到 obj.a.attr1 obj.a.attr2 obj.a.attr3

In the above example I would get obj.a.attr1, obj.a.attr2, obj.a.attr3.

我用 SETATTR 函数,因为我不知道该怎么办 obj.a.NAME 循环。

I used the setattr function because I didn't know how to do obj.a.NAME from a for loop.

如何我设置属性根据 P 在上面的例子中的价值?

How would I set the attribute based on the value of p in the example above?

推荐答案

您可以用我的古代<一个href=\"http://$c$c.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/?in=user-97991\">Bunch食谱,但如果你不想做一个帮班,一个非常简单的已经存在的Python - 所有的功能都可以任意属性(包括lambda函数)。因此,下面的工作:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆