如果我在父类中定义了 __getstate__() 和 __setstate__(),子类是否可以继承这些方法? this SO answer中有一些相关讨论, 但仅限于前面带有双下划线 (dunder) 的方法。
一些额外的信息:
- 我这样做是为了定义我的类的序列化(pickling)行为。
- Python 2.7
请您参考如下方法:
是的,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.
这是一个独立的类,来自__* class-private 名称。
另一个链接的部分是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.
大胆强调我的;以两个下划线开头和以两个下划线结尾的名称不是class-private 名称。
请注意,两个类的名称都是继承的(继承通过在类的 MRO 中查找属性名称来实现)。名称被破坏并不能阻止它们被继承,这就是名称首先被破坏的原因。通过在这些名称前加上 _ClassName 前缀,子类可以重复使用该名称并自动避免冲突,因为它们有自己的 _SubClass 前缀。
