程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

Python 中的继承和多态(python多继承的顺序)

balukai 2025-04-07 11:53:42 文章精选 6 ℃

Python 中的继承是什么?

Python 中的继承是一个特性,允许一个类(子类)使用另一个类(父类)的属性和方法。这有助于我们重用代码并避免重复。

思考一下亲子关系:孩子继承了父母的某些特征,但也可以拥有自己独特的特征。

如何使用 Python 中的继承?

我们创建一个新的类(子类),它从现有的类(父类)中继承。

示例:

# Parent class
class Animal:
    def __init__(self, name):
        self.name = name

    def speak(self):
        return "Some sound"

# Child class inheriting from Animal
class Dog(Animal):
    def speak(self):
        return "Woof! Woof!"

# Child class inheriting from Animal
class Cat(Animal):
    def speak(self):
        return "Meow!"

# Creating objects
dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.name, "says", dog.speak())  # Output: Buddy says Woof! Woof!
print(cat.name, "says", cat.speak())  # Output: Whiskers says Meow!

说明:

  • 动物》类是《父类》。
  • 狗和猫类是子类
  • 每个子类都重写了 speak() 方法。 覆盖

Python 中的继承类型

Python 支持不同的继承类型:

单一继承

一个子类继承自单个父类。

class Vehicle:
    def start_engine(self):
        return "Engine started"

class Car(Vehicle):
    def drive(self):
        return "Car is moving"


my_car = Car()

print(my_car.start_engine())  # Output: Engine started
print(my_car.drive())  # Output: Car is moving

2. 多重继承

一个子类从多个父类继承。

class Animal:
    def eat(self):
        return "Eating food"

class Bird:
    def fly(self):
        return "Flying in the sky"

class Sparrow(Animal, Bird):
    pass

sparrow = Sparrow()

print(sparrow.eat())  # Output: Eating food
print(sparrow.fly())  # Output: Flying in the sky

3. 多级继承

一个子类从另一个子类继承。

class Grandparent:
    def grandparent_method(self):
        return "This is from the grandparent"

class Parent(Grandparent):
    def parent_method(self):
        return "This is from the parent"

class Child(Parent):
    pass

child = Child()

print(child.grandparent_method())  # Output: This is from the grandparent
print(child.parent_method())  # Output: This is from the parent

Python 中的多态是什么?

多态性意味着“多种形式”。它允许我们为不同类型的对象使用相同的方法名。

例如,不同的动物发出不同的声音,但我们为它们都使用相同的函数名( speak())。

多态性示例:

class Dog:
    def speak(self):
        return "Woof!"

class Cat:
    def speak(self):
        return "Meow!"

# Function that uses Polymorphism
def animal_sound(animal):
    return animal.speak()

# Creating objects
dog = Dog()
cat = Cat()

print(animal_sound(dog))  # Output: Woof!
print(animal_sound(cat))  # Output: Meow!

说明:

  • `speak()` 方法在 两个 类中定义。
  • animal_sound()函数调用speak(),但它适用于不同的对象

Python 中的方法重写(多态的一部分)

当一个子类提供了一个已在父类中定义的方法的新实现时,这被称为方法重写

方法重写示例:

class Parent:
    def show(self):
        return "This is the parent class"

class Child(Parent):
    def show(self):
        return "This is the child class"

child_obj = Child()
print(child_obj.show())  # Output: This is the child class

说明:

  • The show() 方法在 Child 类中 重写 了来自 Parent 类的方法。
  • 子类方法替换父类方法。

为什么使用继承和多态?

代码复用性:避免反复编写相同的代码。 更好的组织:将相关功能放在一个地方。 可扩展性:轻松添加新功能而无需修改现有代码。 可读性:代码变得更简单,更容易理解。

结论

  • 继承允许子类使用父类的属性和方法。
  • 多态性允许同一方法对不同类型的对象起作用。
  • 方法重写允许子类替换父类的方法。
最近发表
标签列表