Python极其动态的类属性 [英] Python extremely dynamic class properties

查看:111
本文介绍了Python极其动态的类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在类中创建属性,只需执行 self.property = value 。我想能够让这个类中的属性完全依赖于一个参数。让我们调用 Foo 的实例 Foo



c>类将获取元组的列表:

  l = [(first,foo), ,bar),(anything,you get the point)] 
bar = Foo(l)

现在,分配给 bar Foo 类的实例将具有以下属性:

  bar.first 
#foo
bar.second
#bar
bar.anything
#你得到点

可能?如何?

解决方案

这些称为属性,而不是 / em>。记住这一点,方法 setattr() 变得更明显:

  class Foo(object):
def __init __ ,l):
for k,v in l:
setattr(self,k,v)


b $ b

这会获取 l 中的每个键值对,并在新实例上设置属性 k Foo self )至 v >

使用您的示例:

  l = [(first,foo ),(second,bar),(anything,你得到点)] 
bar = Foo(l)

打印bar.first
#foo
print bar.second
#bar
print bar.anything
#获得点数


To create a property in a class you simply do self.property = value. I want to be able to have the properties in this class completely dependent on a parameter. Let us call this class Foo.

instances of the Foo class would take a list of tuples:

l = [("first","foo"),("second","bar"),("anything","you get the point")]
bar = Foo(l)

now the instance of the Foo class we assigned to bar would have the following properties:

bar.first
#foo
bar.second
#bar
bar.anything
#you get the point

Is this even remotely possible? How?

解决方案

These are called attributes, rather than properties. With that in mind, the method setattr() becomes more obvious:

class Foo(object):
    def __init__(self, l):
        for k, v in l:
            setattr(self, k, v)

This takes each key-value pair in l and sets the attribute k on the new instance of Foo (self) to v.

Using your example:

l = [("first","foo"),("second","bar"),("anything","you get the point")]
bar = Foo(l)

print bar.first
#foo
print bar.second
#bar
print bar.anything
#you get the point

这篇关于Python极其动态的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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