在Python2.6和更高版本中,请考虑namedtuple数据结构适合您的需要:
>>> from collections import namedtuple
>>> MyStruct = namedtuple('MyStruct', 'a b d')
>>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])
>>> s
MyStruct(a=1, b={'c': 2}, d=['hi'])
>>> s.a
1
>>> s.b
{'c': 2}
>>> s.c
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'MyStruct' object has no attribute 'c'
>>> s.d
['hi']
备选方案(最初的答复内容)是:
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
然后,您可以使用:
>>> args = {'a': 1, 'b': 2}
>>> s = Struct(**args)
>>> s
>>> s.a
1
>>> s.b
2