继承的原理,python代码
时间: 2023-02-09 18:02:39 浏览: 60
继承是面向对象编程的一种重要的机制,它允许一个类(称为子类)继承另一个类(称为父类)的方法和属性。这意味着子类可以直接使用父类中定义的方法和属性,并且还可以定义自己的方法和属性。
在 Python 中,使用关键字 `class` 定义一个类,使用关键字 `super()` 调用父类的方法和属性。例如:
```
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
print("Some generic animal sound")
class Cat(Animal):
def __init__(self, name, breed, toy):
super().__init__(name, species="Cat") # Call the superclass's constructor
self.breed = breed
self.toy = toy
def make_sound(self):
print("Meow")
cat1 = Cat("Kitty", "Siamese", "Ball")
print(cat1.name) # Output: "Kitty"
print(cat1.species) # Output: "Cat"
print(cat1.breed) # Output: "Siamese"
print(cat1.toy) # Output: "Ball"
cat1.make_sound() # Output: "Meow"
```
在这个例子中,类 `Cat` 继承自类 `Animal`,并重写了父类的 `make_sound` 方法。当我们创建一个 `Cat` 类型的实例时,我们可以直接使用 `Animal` 类中定义的方法和属性。