Python标准库中有类似JavaScript对象的结构吗?
我经常想要在Python中创建一个简单的“存储”对象,这个对象的用法像JavaScript对象一样(也就是说,它的成员可以用.member
或者['member']
来访问)。
通常我会把这个放在.py
文件的开头:
class DumbObject(dict):
def __getattr__(self, attr):
return self[attr]
def __stattr__(self, attr, value):
self[attr] = value
不过这样做有点无聊,而且这个实现至少有一个bug(虽然我记不起来是什么了)。
那么,标准库里有没有类似的东西呢?
顺便说一下,单纯地实例化object
是行不通的:
>>> obj = object() >>> obj.airspeed = 42 Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'airspeed'
编辑:(真该预料到这一点)…别担心!我并不是想在Python里写JavaScript。我最常需要这个的地方是在我还在实验阶段的时候:我有一堆“东西”,感觉放在字典里不太合适,但也不想为它们单独创建一个类。
10 个回答
14
你可以试试这个叫 attrdict 的东西:
class attrdict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
a = attrdict(x=1, y=2)
print a.x, a.y
print a['x'], a['y']
b = attrdict()
b.x, b.y = 1, 2
print b.x, b.y
print b['x'], b['y']
21
在Python 3.3及以上版本中,你可以使用SimpleNamespace,它正好满足你的需求:
from types import SimpleNamespace
obj = SimpleNamespace()
obj.airspeed = 42
https://docs.python.org/3.4/library/types.html#types.SimpleNamespace