如果你正在使用Python 3.3+,您可以使用types.SimpleNamespace
:
>>> import types
>>> types.SimpleNamespace(a=0, b=0, c=0)
namespace(a=0, b=0, c=0)
>>> obj = types.SimpleNamespace(a=0, b=0, c=0)
>>> obj.a
0
>>> obj.b
0
>>> obj.c
0
在较低的版本,使用collections.namedtuple
,使自定义类型。
>>> from collections import namedtuple
>>>
>>> abc = namedtuple('abc', 'a b c')
>>> abc(a=0, b=0, c=0)
abc(a=0, b=0, c=0)
但它不允许属性设置不同types.SimpleNamespace
:
>>> obj = abc(a=0, b=0, c=0)
>>> obj.a
0
>>> obj.a = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: can't set attribute
为什么你不希望使用一类? –
我不太确定你在问什么。 “class”有什么问题?很难说,也许'collections.namedtuple'可能有帮助。 – AChampion
无论如何,一个类并不是一个真正的数据结构,它是一个可以用来实现具体数据结构的编程结构。 –