当前位置:首页 > 站长知识 > 正文内容

python重写方法实例讲解

2024-09-10站长知识4

1. 重写

重写是基于继承的一种方法,也就是说如果我们不想要从父类中继承来的属性或者行为,我们可以在子类中进行方法的重写。

看下面的例子:

1
2
3
4
5
6
7
8
9
10
11
class Base:#定义一个父类
    def __init__(self,name):
        self.name = name
        print('继承了Base')
    def eat_dinner(self):
        print(self.name,'晚饭吃火锅')
class Student(Base):#继承父类的时候会继承父类中的所有方法
    def eat_dinner(self):
        print(self.name,'晚饭吃自助餐')
xiaoming = Student('小明')
xiaoming.eat_dinner()

输出结果为:

1
2
继承了Base
小明 晚饭吃自助餐

通过这个例子我们可以看出,虽然Student方法继承了Base中的方法并输出了‘继承了Base’,但是当xiaoming使用eat_dinner方法的时候,他使用的是子类重写过后的方法,而不是继承而来的方法。我们在重写的时候需要注意,重写的方法要保持名字和参数的一致性