dunder方法是遗传的吗?

2024-10-02 00:40:42 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我在父类中定义__getstate__()和{},子类是否能够继承这些方法?在this SO answer中有一些相关的讨论,但是只讨论前面有双下划线(dunder)的方法。在

一些额外的信息:

  • 我这样做是为了定义类的序列化(酸洗)行为。在
  • Python 2.7

Tags: 方法answer信息序列化so定义this子类
1条回答
网友
1楼 · 发布于 2024-10-02 00:40:42

是的,dunder方法继承得很好。根据答案,链接的文档是Reserved classes of identifiers

__*__
System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

它是一个独立于__*类私有名称的独立类。在

另一个链接的部分是Identifiers (Names),这可能更清楚:

When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class.

Bold emphasis mine;以两个下划线开头、以两个下划线结尾的名称不是class private名称。在

注意两个名称类都是继承的(继承通过在类的MRO中查找属性名来实现)。名字被弄乱并不能阻止它们被继承,这就是为什么名字首先会被弄乱。通过在这些名称前面加上_ClassName前缀,子类可以重复使用该名称,并且自动不会冲突,因为这些子类有自己的_SubClass前缀。在

相关问题 更多 >

    热门问题