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

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

Mary-Kate Olsen
Release: 2024-12-03 14:14:16
Original
730 people have browsed it

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

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

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

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!

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