Python什么时候以及为什么忽略__slots__?

阿伦·马尼(J Arun Mani)

编辑:人们说它是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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

什么时候以及为什么类型对象比字典更好?

什么时候以及为什么取消功能

什么时候以及为什么在constexpr中使用static?

什么时候以及为什么应该使用域服务?

什么时候以及为什么使用next_by_code()?

.innerHTML与.value ...什么时候以及为什么?

什么时候,为什么以及如何在Python中调用thread.join()?

什么时候以及为什么socket.send()在python中返回0?

什么时候(为什么)引入Python`__new __()`?

什么时候使用(装饰)什么以及为什么-DefaultErpHttpDestination,DefaultHttpDestination?

枚举:为什么?什么时候?

PHP什么时候以及为什么需要调用store_result()?

什么时候以及为什么数据库连接昂贵?

什么时候以及为什么使用tf.reduce_mean?

什么时候以及为什么需要重新导入所有Maven项目?

什么时候,在哪里以及为什么我应该对控制结构使用“替代语法”?

什么时候以及为什么需要Spring应用程序的jboss-deployment-structure.xml?

在Javascript中,什么时候以及为什么数字乘以NaN,然后求值?

什么时候以及为什么要在JavaScript中“返回假”?

什么时候以及为什么要使用-fno-elide-constructors?

什么时候以及为什么我应该使用namedtuple而不是字典?

什么时候以及为什么使用#define macro(x)代替函数?

什么时候以及为什么要在node.js中使用assert?

参数包必须位于参数列表的末尾...什么时候以及为什么?

什么时候以及为什么在C#中使用别名或类名?

什么时候以及为什么要使用没有数据成员的类?

什么时候以及为什么需要在C ++中使用cin.ignore()?

什么时候以及为什么我应该使用session_regenerate_id()?

什么时候以及为什么顺序字段值在Firestore索引豁免中很重要?