杰瑞科技汇

Python继承中,子类如何正确调用父类方法?

Of course! Let's break down Python inheritance, from the basic concept to more advanced features, with clear examples.

What is Inheritance?

Inheritance is a fundamental concept in Object-Oriented Programming (OOP) that allows a new class (called the child or subclass) to adopt and extend the properties and methods of an existing class (called the parent or superclass).

Think of it like a family tree:

  • A Vehicle class might have attributes like color and speed, and methods like start_engine().
  • A Car class is a type of Vehicle. So, it can inherit color, speed, and start_engine() from Vehicle.
  • A Motorcycle class is also a type of Vehicle and can inherit the same things.

The key benefits are:

  1. Code Reusability: You don't have to write the same code for similar classes. The common logic stays in the parent class.
  2. Extensibility: You can add new features to the child class without modifying the parent class.
  3. Logical Structure: It creates a clear and logical hierarchy between classes, making the code easier to understand.

Basic Syntax

To create a child class that inherits from a parent class, you put the parent class's name in parentheses after the child class's name.

# Parent Class (Superclass)
class Animal:
    def __init__(self, name):
        self.name = name
    def speak(self):
        raise NotImplementedError("Subclass must implement this abstract method")
    def eat(self):
        print(f"{self.name} is eating.")
# Child Class (Subclass)
class Dog(Animal):
    def speak(self):
        return f"{self.name} says Woof!"
class Cat(Animal):
    def speak(self):
        return f"{self.name} says Meow!"
# --- Usage ---
my_dog = Dog("Rex")
my_cat = Cat("Whiskers")
print(my_dog.speak())  # Output: Rex says Woof!
print(my_cat.speak())  # Output: Whiskers says Meow!
my_dog.eat()           # Output: Rex is eating. (Inherited from Animal)
my_cat.eat()           # Output: Whiskers is eating. (Inherited from Animal)

In this example:

  • Dog and Cat are subclasses of Animal.
  • They automatically inherit the __init__ method and the eat() method.
  • They provide their own specific implementation for the speak() method.

super(): Calling Parent Methods

Sometimes, you want to add functionality to a method in the child class but still run the original code from the parent class. The super() function is used for this.

It allows you to call methods from the parent class.

Example: Overriding __init__

Imagine the Animal class has more details, and the Dog class wants to add its own specific attribute, like breed.

class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print("Animal constructor called.")
class Dog(Animal):
    def __init__(self, name, age, breed):
        # 1. Call the parent's __init__ method to initialize name and age
        super().__init__(name, age)
        # 2. Now, add the new attribute specific to Dog
        self.breed = breed
        print("Dog constructor called.")
# --- Usage ---
my_dog = Dog("Rex", 5, "Golden Retriever")
print(f"Name: {my_dog.name}")
print(f"Age: {my_dog.age}")
print(f"Breed: {my_dog.breed}")

Output:

Animal constructor called.
Dog constructor called.
Name: Rex
Age: 5
Breed: Golden Retriever

Without super().__init__(name, age), the my_dog object would not have name or age attributes, and you'd get an error.


Types of Inheritance

Python supports several types of inheritance.

Single Inheritance

A child class inherits from only one parent class. This is what we've seen so far.

class A:
    pass
class B(A): # B inherits from A
    pass

Multiple Inheritance

A child class inherits from more than one parent class. Python handles this using the Method Resolution Order (MRO).

class A:
    def method(self):
        print("Method in A")
class B:
    def method(self):
        print("Method in B")
class C(A, B): # C inherits from both A and B
    pass
# --- Usage ---
c = C()
c.method() 

Output:

Method in A

Python looks for method() in C, doesn't find it, then looks in A (the first parent in the list), finds it, and stops. This order is called the MRO. You can see it with print(C.__mro__).

Multilevel Inheritance

A class inherits from a child class, creating a chain.

class A:
    def method_a(self):
        print("Method in A")
class B(A): # B inherits from A
    def method_b(self):
        print("Method in B")
class C(B): # C inherits from B (and indirectly from A)
    def method_c(self):
        print("Method in C")
# --- Usage ---
c = C()
c.method_a() # Inherited from A
c.method_b() # Inherited from B
c.method_c() # Defined in C

Hierarchical Inheritance

Multiple child classes inherit from the same single parent class.

class Animal:
    def speak(self):
        print("Animal sound")
class Dog(Animal): # Dog inherits from Animal
    pass
class Cat(Animal): # Cat also inherits from Animal
    pass

Method Overriding

This is when a child class provides a specific implementation for a method that is already defined in its parent class. We saw this with the speak() method in the Dog and Cat examples.

The child's version of the method "overrides" the parent's version.

class Vehicle:
    def honk(self):
        print("Beep beep!")
class Car(Vehicle):
    # Car inherits honk(), but wants its own version
    def honk(self):
        print("Honk honk!")
my_car = Car()
my_car.honk() # Calls the Car's honk(), not Vehicle's

Output:

Honk honk!

The isinstance() and issubclass() Functions

These are built-in functions that are very useful when working with inheritance.

  • isinstance(object, class): Returns True if the object is an instance of the specified class or a subclass of it.
  • issubclass(class, class): Returns True if a class is a subclass of another class.
class Animal:
    pass
class Dog(Animal):
    pass
my_dog = Dog()
print(isinstance(my_dog, Dog))      # True
print(isinstance(my_dog, Animal))   # True, because Dog is a subclass of Animal
print(isinstance(my_dog, object))    # True, everything in Python is an object!
print(issubclass(Dog, Animal))      # True
print(issubclass(Animal, Dog))      # False

Summary: Key Concepts

Concept Description Example
Parent/Superclass The class being inherited from. class Animal:
Child/Subclass The class that inherits. class Dog(Animal):
Inheritance The mechanism of acquiring properties from a parent. class Dog(Animal):
super() A function to call methods from the parent class. super().__init__(name)
Method Overriding A child class provides its own version of a parent's method. def speak(self): ... in Dog
Method Resolution Order (MRO) The order in which Python looks for a method in a multiple inheritance scenario. print(C.__mro__)
isinstance() Checks if an object is an instance of a class or its subclass. isinstance(my_dog, Animal)
issubclass() Checks if a class is a subclass of another class. issubclass(Dog, Animal)
分享:
扫描分享到社交APP
上一篇
下一篇