简体   繁体   English

在Python中创建具有嵌套属性的空对象

[英]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 : 我不明白你的意思,但是你可以使用namedtuple

>>>from collections import namedtuple

>>>foo = namedtuple('foo', "data tuple dict")
>>>foo.data = ""
''
>>> foo.tuple = ()
>>> foo.tuple
()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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