Python 中 slot wrapper 和 __slots__
Python 的 __slots__ 在使用继承时有什么注意事项?子类如何继承父类的 slots?
回答
我是大山
- 子类有自己的
__slots__:子类也需要声明__slots__才能生效 - 子类没有
__slots__:子类会创建__dict__,父类的__slots__仍然节省内存,但子类实例有__dict__ - 多继承:多个父类都有
__slots__时,子类必须继承自单一__slots__父类,否则报错
class Base:
__slots__ = ('x', 'y')
# 正确:子类也定义 __slots__
class Child(Base):
__slots__ = ('z',)
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
c = Child(1, 2, 3)
# c.w = 4 # AttributeError
# 子类没有 __slots__
class Child2(Base):
pass
c2 = Child2()
c2.x = 1 # OK,来自 __slots__
c2.w = 4 # OK,来自 __dict__
注意:
__slots__可通过__dict__继承时容易被绕开- 多重继承中只有基类之一有
__slots__可正常工作 - 多个
__slots__父类需要协作(使用__slots__元类管理)