Invoking Parent Class Methods from a Child Class in Python
When designing an object hierarchy, it's often necessary to invoke methods from parent classes within derived classes. In languages like Perl and Java, the "super" keyword facilitates this. However, in Python, the approach seems to be different.
Explicit Parent Class Referencing
In Python, it appears that explicitly naming the parent class is the only way to call its methods from a child. For example, if the parent class Foo contains a method frotz, the child class Bar would need to reference it as Foo::frotz().
Limitations and Concerns
This approach could pose challenges in complex hierarchies where children may not always know the class that defined an inherited method. This can lead to maintenance and readability issues.
Super() Function
Fortunately, Python 2.2 and later introduced the super() function to overcome this limitation. super() allows you to access parent class methods directly. Here's an example:
class Foo: def frotz(self): return "Baz" class Bar(Foo): def frotz(self): # Call the parent class's frotz method using super() return super().frotz() + " Quux"
By invoking super().frotz(), the child class Bar can access the frotz method of its parent class Foo.
New-Style Classes
For Python versions prior to 3.0, you must explicitly opt in to using new-style classes. In this case, the syntax is slightly different:
class Foo(Bar): def baz(self, arg): return super(Foo, self).baz(arg)
In these older versions, super takes two arguments: the child class name (e.g., Foo) and the instance object (e.g., self).
The above is the detailed content of How Can I Call Parent Class Methods from Child Classes in Python?. For more information, please follow other related articles on the PHP Chinese website!