Python非常动态的类属性

Rya*_*axe 4 python class

要在类中创建属性,您只需执行此操作self.property = value.我希望能够让这个类中的属性完全依赖于参数.让我们称这个班Foo.

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

l = [("first","foo"),("second","bar"),("anything","you get the point")]
bar = Foo(l)
Run Code Online (Sandbox Code Playgroud)

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

bar.first
#foo
bar.second
#bar
bar.anything
#you get the point
Run Code Online (Sandbox Code Playgroud)

这甚至可以远程实现吗?怎么样?

Ter*_*ryA 6

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

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

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

  • 这是非常有创意和压缩...... + 1 (2认同)