3

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
martineau
  • 119,623
  • 25
  • 170
  • 301
BoltzmannBrain
  • 5,082
  • 11
  • 46
  • 79
  • @MSeifert class-private names (i.e., `__*`) are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. I'm unsure if dunder dunder methods fall in this boat. – BoltzmannBrain Jun 08 '17 at 20:13
  • 1
    No they don't - because they don't classify as "private attributes" (these are defined as "at least two leading underscores, at most one trailing underscore"): see https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references – MSeifert Jun 08 '17 at 20:19

2 Answers2

6

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

There is an exception for __repr__ which is not inherited.

Allen Wang
  • 2,426
  • 2
  • 24
  • 48