很多时候,我发现自己想在Python中使用一个简单的"转储"对象,其行为类似于JavaScript对象(即,其成员可以使用.member或使用['member']).
通常我会把它放在以下的顶部.py:
class DumbObject(dict):
def __getattr__(self, attr):
return self[attr]
def __stattr__(self, attr, value):
self[attr] = value
Run Code Online (Sandbox Code Playgroud)
但这有点蹩脚,并且该实现至少存在一个错误(尽管我不记得它是什么).
那么,标准库中有类似的东西吗?
并且,为了记录,简单的实例化object不起作用:
>>> obj = object() >>> obj.airspeed = 42 Traceback (most recent call last): File "", line 1, in AttributeError: 'object' object has no attribute 'airspeed'
编辑 :(当,应该看到这一个来了)...别担心!我不是想用Python编写JavaScript.我经常发现我想要的地方就是在我还在试验的时候:我有一些"东西"的集合,这些东西不太适合放入字典,但也不适合拥有自己的课程.
ars*_*ars 12
你可以试试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']
Run Code Online (Sandbox Code Playgroud)
bsc*_*can 10
在 Python 3.3+ 中,您可以使用 SimpleNamespace,它完全符合您的要求:
from types import SimpleNamespace
obj = SimpleNamespace()
obj.airspeed = 42
Run Code Online (Sandbox Code Playgroud)
https://docs.python.org/3.4/library/types.html#types.SimpleNamespace
小智 6
如果我理解正确,您需要一个可以转储属性的对象.如果我是对的,你所要做的就是创建一个空类.例如:
>>> class DumpObject: pass
...
>>>#example of usage:
...
>>> a = DumpObject()
>>> a.airspeed = 420
>>> print a.airspeed
420
Run Code Online (Sandbox Code Playgroud)
而已