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

How Do I Call Parent Class Methods in Python Inheritance?

Susan Sarandon
Release: 2024-11-27 04:04:10
Original
517 people have browsed it

How Do I Call Parent Class Methods in Python Inheritance?

Calling Parent Class Methods in Python

Python's inheritance mechanism allows derived classes to access base class methods, but unlike Perl or Java, it doesn't provide a keyword like "super". Instead, you need to explicitly reference the parent class.

Example:

Consider the following example where the Bar class extends the Foo class:

class Foo:
    def frotz(self):
        return "Bamf"

class Bar(Foo):
    def frotz(self):
        # Attempt to explicitly call the parent class 'frotz' method
        return Foo.frotz(self)
Copy after login

This approach requires specifying the parent class explicitly, making it inconvenient for deep hierarchies.

Solution: Using the 'super()' Function

Python 2.2 and later introduced the super() function, which provides a more elegant solution:

class Bar(Foo):
    def frotz(self):
        # Now calling 'frotz' using the 'super()' function
        return super().frotz()
Copy after login

The super() function intelligently determines the parent class to inherit from, based on the context in the derived class. This eliminates the need to specify the parent class explicitly.

For Python < 3:

However, for Python versions prior to 3, you must explicitly opt into using new-style classes:

class Foo(object):
    def baz(self):
        pass

class Bar(Foo):
    def baz(self, arg):
        return super(Bar, self).baz(arg)  # Explicitly specifying 'Bar' as parent
Copy after login

The object base class is used to enable new-style class syntax.

So, in Python, calling parent class methods from derived classes is possible using the 'super()' function (preferred) or by explicitly referencing the parent class (only necessary for Python < 3).

The above is the detailed content of How Do I Call Parent Class Methods in Python Inheritance?. 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