问题描述
如果我在父类中定义了__getstate__()
和__setstate__()
,那么子级是否可以继承这些方法?在此SO答案中有一些相关的讨论,但仅涉及带有双引号(dunder)的方法.
If I define __getstate__()
and __setstate__()
in a parent class, would a child be able to inherit these methods? There's some related discussion in this SO answer, but only on methods with a preceding double-underscore (dunder).
一些额外的信息:
- 我这样做是为了定义我的类的序列化(腌制)行为.
- Python 2.7
推荐答案
是的,dunder方法可以很好地继承.从那里的答案中,链接的文档为 保留的标识符类别 :
Yes, dunder methods are inherited just fine. From the answer there, the documentation linked is Reserved classes of identifiers:
是与__*
class-private 名称分开的单独的类.
和链接的其他部分为 标识符(名称) 也许仍然更清楚:
and the other section linked is Identifiers (Names) which is perhaps clearer still:
强调粗体的地雷;以两个下划线开头和以两个下划线结尾的名称不是 class-private 名称.
Bold emphasis mine; names that start with two underscores and end with two underscores are not class-private names.
请注意,名称的两个 类都是继承的(继承是通过在该类的MRO中查找属性名称来实现的).名称被重整并不能阻止它们被继承,这就是为什么为什么首先被重命名.通过为这些名称加上_ClassName
前缀,子类可以重用该名称,并且不会自动冲突,因为这些子类具有自己的_SubClass
前缀.
Note that both classes of names are inherited (inheritance works by looking up attribute names in the MRO of the class). That names are mangled doesn't prevent them from being inherited, which is why the names are mangled in the first place. By prefixing such names with _ClassName
subclasses can re-use the name and automatically not clash because these get their own _SubClass
prefix.
这篇关于dunder方法是继承的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!