super和extend
时间: 2023-11-11 07:58:32 浏览: 32
`super` 和 `extend` 都是面向对象编程中的关键字。
`super` 是一个指向父类(或超类)的指针,可以用来调用父类的方法或属性。通过 `super`,我们可以在子类中使用父类的构造函数和方法,以达到代码复用的目的。
例如,在子类中调用父类的构造函数:
```python
class Animal:
def __init__(self, name):
self.name = name
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
```
在上述代码中,`Cat` 类继承自 `Animal` 类。在 `Cat` 类的构造函数中,我们通过 `super().__init__(name)` 调用了父类 `Animal` 的构造函数,以初始化 `name` 属性。
`extend` 则是用来扩展一个类的功能,通常是通过继承来实现。当一个类继承自另一个类时,它可以获得父类的属性和方法,并且可以在此基础上添加新的属性和方法。
例如:
```python
class Animal:
def __init__(self, name):
self.name = name
def say_hello(self):
print("Hello, I'm an animal.")
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name)
self.color = color
def say_hello(self):
print("Hello, I'm a cat.")
def catch_mouse(self):
print("I'm catching a mouse.")
```
在上述代码中,`Cat` 类继承自 `Animal` 类,并且添加了新的方法 `catch_mouse`。同时,`Cat` 类重写了父类 `Animal` 的方法 `say_hello`,以改变输出的内容。这样,`Cat` 类就扩展了 `Animal` 类的功能。