Kna*_*ack 15 python inheritance slots
我需要使用None初始化实例的所有插槽.如何获取派生类的所有插槽?
示例(不起作用):
class A(object):
__slots__ = "a"
def __init__(self):
# this does not work for inherited classes
for slot in type(self).__slots__:
setattr(self, slot, None)
class B(A):
__slots__ = "b"
Run Code Online (Sandbox Code Playgroud)
我可以使用一个额外的class属性来保存所有类的槽(包括继承的),比如
class A(object):
__slots__ = "a"
all_slots = "a"
def __init__(self):
# this does not work for inherited classes
for slot in type(self).all_slots:
setattr(self, slot, None)
class B(A):
__slots__ = "b"
all_slots = ["a", "b"]
Run Code Online (Sandbox Code Playgroud)
但这似乎不是最理想的.
任何评论表示赞赏!
干杯,
一月
Flo*_*yer 14
首先,它是
class A(object):
__slots__ = ('a',)
class B(A):
__slots__ = ('b',)
Run Code Online (Sandbox Code Playgroud)
制作包含__slots__
B或其任何父类所包含的所有元素的列表将是:
from itertools import chain
slots = chain.from_iterable(getattr(cls, '__slots__', []) for cls in B.__mro__)
Run Code Online (Sandbox Code Playgroud)
您想迭代MRO中的每个类:
class A(object):
__slots__ = ('x', 'y')
def __init__(self):
for slots in [getattr(cls, '__slots__', []) for cls in type(self).__mro__]:
for attr in slots:
setattr(self, attr, None)
Run Code Online (Sandbox Code Playgroud)
您可以看到这在派生类中按预期工作:
class B(A):
__slots__ = ('z',)
>>> b = B()
>>> b.x, b.y, b.z
<<< (None, None, None)
Run Code Online (Sandbox Code Playgroud)