社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python何时以及为什么忽略插槽?[副本]

J Arun Mani • 4 年前 • 690 次点击  

编辑:人们说它是 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社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/47877
 
690 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Cireo
Reply   •   1 楼
Cireo    4 年前

你的问题在里面有答案 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.

尤其是,你必须有一个完整的 __slots__ 从最初的 object 继承到当前类,否则您将拥有 __dict__ 可用,插槽将无法阻止修改。

对象不使用槽,所以不能使用它的子类来阻止设置属性