Home > Backend Development > Python Tutorial > How Can I Call Parent Class Methods in Python?

How Can I Call Parent Class Methods in Python?

Susan Sarandon
Release: 2024-11-28 04:46:14
Original
545 people have browsed it

How Can I Call Parent Class Methods in Python?

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template