Are dunder methods inherited?

Question:

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).

Some extra info:

  • I’m doing this to define serialization (pickling) behavior of my classes.
  • Python 2.7
Asked By: BoltzmannBrain

||

Answers:

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 _SubClass prefix.

Answered By: Martijn Pieters

There is an exception for __repr__ which is not inherited.

Answered By: Allen Wang
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.