Home >Backend Development >Python Tutorial >How Do I Call Parent Class Methods from Child Classes in Python?

How Do I Call Parent Class Methods from Child Classes in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-08 13:59:14392browse

How Do I Call Parent Class Methods from Child Classes in Python?

Calling Parent Class Methods in Python Child Classes

When defining class hierarchies in Python, it's crucial to know how to access parent class methods from derived classes. In languages like Perl and Java, the keyword "super" facilitates this, but in Python, there's a seemingly different approach.

Introducing the super() Function

To invoke a parent class method from a child class in Python, use the super() function. This function allows you to access parent class attributes and methods without explicitly specifying the parent class name.

class Foo(Bar):
    def baz(self, **kwargs):
        return super().baz(**kwargs)

In the example above, the Foo class is a child of the Bar class. Inside the baz method of the Foo class, super() is used to call the baz method of the parent Bar class.

Opting into New-Style Classes (Python 2 only)

In Python 2, you must explicitly opt into using new-style classes to utilize the super() function. To do this, declare the parent class using the super keyword:

class Foo(Bar):
    def baz(self, arg):
        return super(Foo, self).baz(arg)

By embracing the super() function, you simplify your codebase, reduce coupling between classes, and enhance the maintainability of your deep class hierarchies in Python.

The above is the detailed content of How Do I Call Parent Class Methods from Child Classes in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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