使用super的例子python代码
时间: 2023-07-23 22:07:23 浏览: 39
下面是一个使用`super()`的Python代码示例:
```python
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
print("Some generic sound")
class Cat(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def make_sound(self):
print("Meow!")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def make_sound(self):
print("Woof!")
cat = Cat("Whiskers", "Siamese")
dog = Dog("Fido", "Golden Retriever")
print(cat.name) # Output: Whiskers
print(cat.breed) # Output: Siamese
cat.make_sound() # Output: Meow!
print(dog.name) # Output: Fido
print(dog.breed) # Output: Golden Retriever
dog.make_sound() # Output: Woof!
```
在上面的代码中,`Cat`和`Dog`类都继承自父类`Animal`。在子类的`__init__()`方法中使用`super()`函数调用父类的`__init__()`方法来初始化继承的属性。在子类中也重新定义了`make_sound()`方法,子类对象调用该方法时会优先调用子类中的方法。