python中类的继承的例子
时间: 2023-09-12 13:08:17 浏览: 41
下面是一个简单的Python类继承的例子,其中有一个父类`Animal`和两个子类`Dog`和`Cat`,它们都继承了`Animal`类的属性和方法:
```python
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
pass
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age)
self.breed = breed
def speak(self):
return "Woof"
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age)
self.color = color
def speak(self):
return "Meow"
dog = Dog("Buddy", 5, "Golden Retriever")
cat = Cat("Whiskers", 3, "Orange")
print(dog.name) # Output: Buddy
print(cat.age) # Output: 3
print(dog.breed) # Output: Golden Retriever
print(dog.speak()) # Output: Woof
print(cat.speak()) # Output: Meow
```
在上面的例子中,`Dog`和`Cat`都继承了`Animal`类的构造函数和`speak`方法,但是它们都有自己的特定属性和方法。在创建子类的对象时,还可以使用`super()`函数来调用父类的构造函数,以便在子类中初始化父类的属性。