4

要在一个类中创建一个属性,您只需这样做self.property = value。我希望能够使此类中的属性完全依赖于参数。让我们称之为这个类Foo

该类的实例Foo将采用元组列表:

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

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

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

这甚至有可能吗?如何?

4

5 回答 5

6

我想到了另一个你可以使用的答案type()。这与我当前的答案完全不同,所以我添加了一个不同的答案:

>>> bar = type('Foo', (), dict(l))()
>>> bar.first
'foo'
>>> bar.second
'bar'
>>> bar.anything
'you get the point'

type()返回一个,而不是一个实例,因此最后是额外()的。

于 2013-10-06T02:59:25.343 回答
4

这些被称为属性,而不是属性。考虑到这一点,该方法setattr()变得更加明显:

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

这会将每个键值对放入l并将( )k的新实例上的属性设置为。Fooselfv

使用您的示例:

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
于 2013-10-06T02:41:39.780 回答
3

There are two ways to do this:

  • Use setattr like this. This approach is feasible if you only need to process the initial list once, when the object is constructed.

    class Foo:
      def __init__(self, l):
        for (a, b) in l:
          setattr(self, a, b)
    
  • Define a custom __getattr__ method. Preferably, you would store the properties in a dict for faster lookup, but you can also search the original list. This is better if you want to later modify the list and want this to be reflected in the attributes of the object.

    class Foo:
      def __init__(self, l):
        self.l = l
      def __getattr__(self, name):
        for a in self.l:
          if a[0] == name:
            return a[1]
        return None
    
于 2013-10-06T02:49:02.840 回答
2

像这样的东西?

>>> class Foo:
...     def __init__(self, mylist):
...         for k, v in mylist:
...             setattr(self, k, v)
... 
>>> l = [("first","foo"),("second","bar"),("anything","you get the point")]
>>> bar = Foo(l)
>>> bar.first
'foo'
>>> bar.second
'bar'
>>> bar.anything
'you get the point'

使用setattr你可以通过传入列表并迭代它来做到这一点。

于 2013-10-06T02:41:15.307 回答
-1

setattr 有效。

>>> class Foo:
...   def __init__(self,yahoo):
...     for k,v in yahoo:
...       setattr(self,k,v)
...
>>> 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
于 2013-10-06T02:43:52.980 回答