如何创建对象并向其添加属性? [英] How can I create an object and add attributes to it?

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

问题描述

我想在 Python 中创建一个动态对象(在另一个对象内),然后为其添加属性.

我试过了:

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

但这没有用.

有什么想法吗?

我正在从一个 for 循环中设置属性,该循环遍历一个值列表,例如

params = ['attr1', 'attr2', 'attr3']obj = 某个对象obj.a = 对象()对于参数中的 p:obj.a.p # 其中 p 来自 for 循环变量

在上面的例子中,我会得到 obj.a.attr1obj.a.attr2obj.a.attr3.

我使用了 setattr 函数,因为我不知道如何从 for 循环中执行 obj.a.NAME.>

如何根据上面例子中的 p 的值设置属性?

解决方案

你可以使用我古老的 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.

这篇关于如何创建对象并向其添加属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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