Use the __slots__
属性加成getattr()在字典理解中:
{
s: getattr(obj, s)
for s in {
s
for cls in type(obj).__mro__
for s in getattr(cls, '__slots__', ())
}
if hasattr(obj, s)
}
它从所有基类收集插槽名称并跳过任何未设置的属性。
或者,将缺失的属性设置为None
:
{
s: getattr(obj, s, None)
for s in {
s
for cls in type(obj).__mro__
for s in getattr(cls, '__slots__', ())
}
}
Demo:
>>> class Foo(object):
... __slots__ = ('bar', 'spam')
...
>>> obj = Foo()
>>> obj.bar = 42
>>> {s: getattr(obj, s) for s in {s for cls in type(obj).__mro__ for s in getattr(cls, '__slots__', ())} if hasattr(obj, s)}
{'bar': 42}
>>> {s: getattr(obj, s, None) for s in {s for cls in type(obj).__mro__ for s in getattr(cls, '__slots__', ())}}
{'spam': None, 'bar': 42}
您甚至可以将其作为班级的财产vars()
将利用它:
>>> class Foo(object):
... __slots__ = ('bar', 'spam')
... @property
... def __dict__(self):
... return {
... s: getattr(self, s)
... for s in {
... s
... for cls in type(self).__mro__
... for s in getattr(cls, '__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'