如何将带有插槽的 python 类转换为字典? [英] How can I convert python class with slots to dictionary?
本文介绍了如何将带有插槽的 python 类转换为字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用带插槽的类来减少实例将占用的内存.现在,如何将插槽实例转换为字典?
槽类看起来像这样:
class Foo(object):__slots__ = ['x','y','z']def __init__(self):自我.x = 1自我.y = 2self.z = 3
我期待这样的事情:
y = Foo()y.__dict__{'x':1,'y':2,'z':3}
解决方案
使用 __slots__
属性加上 getattr()
在字典理解中:
{s: getattr(obj, s) for s in obj.__slots__ if hasattr(obj, s)}
跳过任何未设置的属性.
替代方法,将缺少的属性设置为 None
:
{s: getattr(obj, s, None) for s in obj.__slots__}
演示:
<预><代码>>>>类 Foo(对象):... __slots__ = ('bar', '垃圾邮件')...>>>obj = Foo()>>>obj.bar = 42>>>{s: getattr(obj, s) for s in obj.__slots__ if hasattr(obj, s)}{'条':42}>>>{s: getattr(obj, s, None) for s in obj.__slots__}{'垃圾邮件':无,'bar':42}您甚至可以将其设为类的属性,vars()
将使用它:
I am using class with slots to reduce the memory which the instance will occupy. Now, how can I convert a slot instance to dictionary ?
The slot class look like this :
class Foo(object):
__slots__ = ['x','y','z']
def __init__(self):
self.x = 1
self.y = 2
self.z = 3
I expect something like this:
y = Foo()
y.__dict__
{'x': 1, 'y': 2, 'z': 3}
解决方案
Use the __slots__
attribute plus getattr()
in a dictionary comprehension:
{s: getattr(obj, s) for s in obj.__slots__ if hasattr(obj, s)}
which skips any attributes not set.
Alternative, setting missing attributes to None
:
{s: getattr(obj, s, None) for s in obj.__slots__}
Demo:
>>> 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}
You can even make that a property of the class and vars()
will make use of it:
>>> 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'
这篇关于如何将带有插槽的 python 类转换为字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文