Python - 类继承

在Python中,类继承是一种机制,允许一个类继承另一个类的属性和方法。
通过这种方式,子类可以继承超类的所有属性和方法,并且还可以添加自己的属性和方法。

✏️ 语法

python
class 超类名:
    # 超类的属性和方法

class 子类名(超类名):
    # 子类的属性和方法
  • 使用class关键字定义超类,后面跟着超类的名称。
  • 使用class关键字定义子类,后面跟着子类的名称。
    然后,在一对括号中填写超类的名称。

📘 示例

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

    def speak(self):
        print("我是", self.name)

class Dog(Animal):
    def __init__(self, name, weight):
        super().__init__(name)
        self.weight = weight

    def getWeight(self):
        print("体重", self.weight)

class Cat(Animal):
    def __init__(self, name, color):
        super().__init__(name)
        self.color = color

    def getColor(self):
        print("颜色", self.color)

dog = Dog("Snoopy", 20)
dog.speak()
dog.getWeight()

cat = Cat("kitty", "白色")
cat.speak()
cat.getColor()

在上面的示例中,Animal是超类,DogCat是子类。
子类继承了超类的属性和方法,并且还可以添加自己的属性和方法。
在子类中,如果需要调用超类的方法,可以使用super()函数来实现。