python中什么是类的继承
时间: 2024-01-29 10:04:36 浏览: 25
在Python中,类的继承是一种机制,允许一个类(称为子类或派生类)继承另一个类(称为父类或基类)的属性和方法。子类可以从父类继承所有的公共属性和方法,同时可以添加自己的属性和方法,或者重写父类的方法。
在Python中,子类可以通过以下方式继承父类的属性和方法:
```python
class ParentClass:
# 父类的属性和方法
class ChildClass(ParentClass):
# 子类继承父类的所有属性和方法
```
在这个例子中,我们定义了一个ParentClass父类和一个ChildClass子类,子类通过继承父类的方式获得了父类的所有属性和方法。
如果子类想要重写父类的方法或者添加自己的属性和方法,可以直接在子类中定义对应的方法或者属性即可。在子类中访问父类的属性和方法时,可以使用super()函数来实现。例如:
```python
class ParentClass:
def say_hello(self):
print("Hello, I'm the parent.")
class ChildClass(ParentClass):
def say_hello(self):
super().say_hello()
print("Hello, I'm the child.")
```
在这个例子中,我们定义了一个ParentClass父类和一个ChildClass子类,子类重写了父类的say_hello()方法,并且使用super().say_hello()来调用父类的say_hello()方法。这样,当我们调用ChildClass的say_hello()方法时,输出将是:“Hello, I'm the parent.”和“Hello, I'm the child.”。