Calling Parent Class Methods in Python
When working with object hierarchies in Python, it may be necessary to invoke methods from a parent class within a child class. Unlike Perl or Java, where specific keywords exist for this purpose, Python requires the use of explicit parent class references.
In the example provided, the code using Foo::frotz() is not ideal as it forces child classes to know which class defined inherited methods, leading to information dependencies and potential issues when creating deep hierarchies.
To resolve this, Python offers the super() function. Using super(), you can access and call parent class methods from a child class without explicitly specifying the parent class name.
For Python 3 and later, you can simply use:
class Foo(Bar): def baz(self, **kwargs): return super().baz(**kwargs)
For Python 2, you must explicitly enable new-style classes and use:
class Foo(Bar): def baz(self, arg): return super(Foo, self).baz(arg)
The above is the detailed content of How Can I Call Parent Class Methods in Python?. For more information, please follow other related articles on the PHP Chinese website!