When one has a class that inherits from a single class, what is the preferred, and most pythonic, way to call parent methods? There are two ways that I know of to call the parent method.
Option 1:
ParentClass.method(self, *args, **kwargs)
Option 2:
super(MyClass, self).method(*args, **kwargs)
Option 1 definitely seems to make a lot of sense when dealing with multiple inheritance; we want to specifically call the method of a certain class. But when dealing with single inheritance, either way works, though Option 1 is probably more future safe. But is there anything (like a PEP) that says when to use which style?
First of all, if you have old-style classes you need to use Option 1 .
If not, it depends on the code:
super
(or nothing), you can safely use super. This also means your subclsses must use super
instead of Parent.method(self, ...)
. Parent.method(self, ...)
, also use it. There's a good and much more verbose explanation at http://fuhm.net/super-harmful/ . The short summary (even shorter than my explanation above):
- Subclasses must use super if their superclasses do
- Superclasses must use super if their subclasses do (sometimes)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.