编辑:人们说它是Python的副本:子类中__slots__的继承实际上如何工作?。它不是。上述问题的公认答案甚至没有帮助或让我有点理解。但是我接受的答案说__slots__的用法?有我想要的答案inside
,这可能是正确的。
在编写以下代码块时,我陷入了困境。Python会忽略任何地方__slots__
吗?
假设演示代码如下。(GObject是一个抽象对象,用于制作Gtk小部件。)
class A:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
class B(A):
__slots__ = ("z",)
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
class C(A):
__slots__ = ("w",)
def __init__(self, x, y, z):
super().__init__(x, y)
self.z = z
class D(GObject.Object):
__slots__ = ("w",)
def __init__(self, z):
super().__init__()
self.z = z
b = B(1, 2, 3)
#c = C(1, 2, 3) # Results in AttributeError: 'C' object has no attribute 'z'
d = D(10) # No Error! ^^
#b.p = 3 # AttributeError
d.p = 3 # No Error ^*
请解释为什么D
什么都没得到的原因AttributeError
。
__slots__的用法内回答了您的问题?
Requirements:
To have attributes named in __slots__ to actually be
stored in slots instead of a __dict__, a class must
inherit from object.
To prevent the creation of a __dict__, you must
inherit from object and all classes in the inheritance
must declare __slots__ and none of them can
have a '__dict__' entry.
特别是,您必须具有__slots__
从原始object
继承到当前类的完整链,否则您将拥有一个__dict__
可用链,并且插槽将无法阻止修改。
tl; dr:GObject.Object不使用插槽,因此您不能使用其子类来防止设置属性
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句