[英]How to gather all __slots__ for a class
考虑以下代码:
class A(object):
__slots__ = "a", "b"
def __init__(self, a, b):
self.a = a
self.b = b
class B(A):
__slots__ = "c",
def __init__(self, a, b, c):
super(B, self).__init__(a, b)
self.c = c
b = B(1, 2, 3)
print(b.__slots__) # Prints just "('c',)", but I want to get ("a", "b", "c")
对于B
类实例,我希望能够访问其所有父类中声明的所有插槽。 有可能吗?
class A(object):
__slots__ = "a", "b"
def __init__(self, a, b):
self.a = a
self.b = b
class B(A):
__slots__ = "c",
def __init__(self, a, b, c):
super(B, self).__init__(a, b)
self.c = c
b = B(1, 2, 3)
def all_slots(obj):
slots = set()
for cls in obj.__class__.__mro__:
slots.update(getattr(cls, '__slots__', []))
return slots
print(all_slots(b))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.