我正在使用带槽的类来减少实例占用的内存.现在,我如何将插槽实例转换为字典?
插槽类看起来像这样:
class Foo(object):
__slots__ = ['x','y','z']
def __init__(self):
self.x = 1
self.y = 2
self.z = 3
Run Code Online (Sandbox Code Playgroud)
我期待这样的事情:
y = Foo()
y.__dict__
{'x': 1, 'y': 2, 'z': 3}
Run Code Online (Sandbox Code Playgroud)
在字典理解中使用__slots__属性plus getattr():
{s: getattr(obj, s) for s in obj.__slots__ if hasattr(obj, s)}
Run Code Online (Sandbox Code Playgroud)
跳过未设置的任何属性.
另外,将缺少的属性设置为None:
{s: getattr(obj, s, None) for s in obj.__slots__}
Run Code Online (Sandbox Code Playgroud)
演示:
>>> class Foo(object):
... __slots__ = ('bar', 'spam')
...
>>> obj = Foo()
>>> obj.bar = 42
>>> {s: getattr(obj, s) for s in obj.__slots__ if hasattr(obj, s)}
{'bar': 42}
>>> {s: getattr(obj, s, None) for s in obj.__slots__}
{'spam': None, 'bar': 42}
Run Code Online (Sandbox Code Playgroud)
您甚至可以将其作为该类的属性并vars()使用它:
>>> class Foo(object):
... __slots__ = ('bar', 'spam')
... @property
... def __dict__(self):
... return {s: getattr(self, s) for s in self.__slots__ if hasattr(self, s)}
...
>>> f = Foo()
>>> f.bar = 42
>>> f.__dict__
{'bar': 42}
>>> f.spam = 'eggs'
>>> f.__dict__
{'spam': 'eggs', 'bar': 42}
>>> vars(f)
{'spam': 'eggs', 'bar': 42}
>>> f.hello = 'world'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute 'hello'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1884 次 |
| 最近记录: |