定义两个类时,一个带有__dict__实现(A),另一个带有__slots__实现(B)。
是否有一种聪明的方法来获取__slots__类的实例属性名称和值,就像在__dict__类上使用vars()函数一样?
class A(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class B(object):
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
vars(A(1, 2, 3)) # {'y': 2, 'x': 1, 'z': 3}
vars(B(1, 2, 3)) # TypeError: vars() argument must have __dict__ attribute
使用带有检查的.__ slots__或dir()只返回属性名称,不带值
B(1, 2, 3).__slots__ # ('x', 'y', 'z')
答案 0 :(得分:3)
这是我之前使用过的一个函数:
def vars2(obj):
try:
return vars(obj)
except TypeError:
return {k: getattr(obj, k) for k in obj.__slots__}
答案 1 :(得分:1)
In [2]: x = B(1,2,3)
In [3]: {a: x.__getattribute__(a) for a in dir(x)}
Out[3]:
{'__class__': __main__.B,
'__delattr__': <method-wrapper '__delattr__' of B object at 0x7f3bb2b48e18>,
'__doc__': None,
'__format__': <function __format__>,
'__getattribute__': <method-wrapper '__getattribute__' of B object at 0x7f3bb2b48e18>,
'__hash__': <method-wrapper '__hash__' of B object at 0x7f3bb2b48e18>,
'__init__': <bound method B.__init__ of <__main__.B object at 0x7f3bb2b48e18>>,
'__module__': '__main__',
'__new__': <function __new__>,
'__reduce__': <function __reduce__>,
'__reduce_ex__': <function __reduce_ex__>,
'__repr__': <method-wrapper '__repr__' of B object at 0x7f3bb2b48e18>,
'__setattr__': <method-wrapper '__setattr__' of B object at 0x7f3bb2b48e18>,
'__sizeof__': <function __sizeof__>,
'__slots__': ('x', 'y', 'z'),
'__str__': <method-wrapper '__str__' of B object at 0x7f3bb2b48e18>,
'__subclasshook__': <function __subclasshook__>,
'x': 1,
'y': 2,
'z': 3}
或者,如果你不想看到魔术方法:
In [4]: {a: x.__getattribute__(a) for a in dir(x) if not a.startswith('__')}
Out[4]: {'x': 1, 'y': 2, 'z': 3}