If I define
__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).
Some extra info:
Yes, dunder methods are inherited just fine. From the answer there, the documentation linked is 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.
which is a separate class from
__* class-private names.
and the other section linked is Identifiers (Names) which is perhaps clearer still:
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; names that start with two underscores and end with two underscores are not class-private names.
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
There is an exception for
__repr__ which is not inherited.