简体   繁体   中英

Creating an empty object with nested attributes in Python

I'm trying to create an empty object which contains nested attributes like this:

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

But I get following attribute error:

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

How should I construct the object to accomplish that?

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}) 

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
()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM