【问题标题】:When and why does Python ignore __slots__? [duplicate]Python 何时以及为何忽略 __slots__? [复制]
【发布时间】:2020-02-22 02:46:19
【问题描述】:

编辑:人们说它是Python: How does inheritance of __slots__ in subclasses actually work? 的副本。它不是。上述问题的公认答案甚至没有帮助或让我有点理解它。但我接受的答案是 Usage of __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 的原因。

【问题讨论】:

  • 这就是我要问的。不,它不是错字。它的问题。 Python 给了我预期的错误。但在D 中,没有错误。为什么?
  • 我认为你在C 中弄乱了你的错误消息——我不明白为什么当你分配给属性z 时它会说“没有属性'w'”。 ..
  • 抱歉,是的,我明白您对D 的询问——这只是C 的错误消息,与我所期望的不太一样
  • 操作。对不起。那应该是c。但感觉是一样的。

标签: python


【解决方案1】:

您的问题在Usage of __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.

特别是,您必须有一个从原始object 继承到当前类的只有__slots__ 的完整链,否则您将拥有可用的__dict__,并且插槽将无法阻止修改。

tl;dr: GObject.Object 不使用槽,所以你不能使用它的子类来防止设置属性

【讨论】:

    猜你喜欢
    • 2012-06-23
    • 2010-10-09
    • 2016-08-29
    • 2018-01-19
    • 2011-08-02
    • 1970-01-01
    • 2020-06-30
    • 2018-06-21
    • 2012-12-24
    相关资源
    最近更新 更多