在Python中使用嵌套属性创建一个空对象

时间:2016-12-09 12:31:26

标签: python object attributes nested

我试图创建一个包含嵌套属性的空对象:

form = type('', (), {})()
form.foo.data = ''

但我得到以下属性错误:

>>> form = type('', (), {})()
>>> form.foo.data = ''
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'data'

我应该如何构建对象来实现它?

2 个答案:

答案 0 :(得分:1)

As per the type function , the third argument should be in the form of dictionary. So, for nested attributes, you can create the object before itself and then use it in the dictionary. Something like this might work -

da = type('',(),{'data':1})    
a = type('',(),{'foo':da}) 

答案 1 :(得分:0)

I dont get your point but you may use namedtuple :

>>>from collections import namedtuple

>>>foo = namedtuple('foo', "data tuple dict")
>>>foo.data = ""
''
>>> foo.tuple = ()
>>> foo.tuple
()
相关问题