Calling Parent Class Methods in Python
Python's inheritance mechanism allows derived classes to access base class methods, but unlike Perl or Java, it doesn't provide a keyword like "super". Instead, you need to explicitly reference the parent class.
Example:
Consider the following example where the Bar class extends the Foo class:
class Foo: def frotz(self): return "Bamf" class Bar(Foo): def frotz(self): # Attempt to explicitly call the parent class 'frotz' method return Foo.frotz(self)
This approach requires specifying the parent class explicitly, making it inconvenient for deep hierarchies.
Solution: Using the 'super()' Function
Python 2.2 and later introduced the super() function, which provides a more elegant solution:
class Bar(Foo): def frotz(self): # Now calling 'frotz' using the 'super()' function return super().frotz()
The super() function intelligently determines the parent class to inherit from, based on the context in the derived class. This eliminates the need to specify the parent class explicitly.
For Python < 3:
However, for Python versions prior to 3, you must explicitly opt into using new-style classes:
class Foo(object): def baz(self): pass class Bar(Foo): def baz(self, arg): return super(Bar, self).baz(arg) # Explicitly specifying 'Bar' as parent
The object base class is used to enable new-style class syntax.
So, in Python, calling parent class methods from derived classes is possible using the 'super()' function (preferred) or by explicitly referencing the parent class (only necessary for Python < 3).
The above is the detailed content of How Do I Call Parent Class Methods in Python Inheritance?. For more information, please follow other related articles on the PHP Chinese website!