Python:多态

大数据学习路线图

【版权声明】博客内容由厦门大学数据库实验室拥有版权,未经允许,请勿转载!版权所有,侵权必究!
[返回Python教程首页]

多态

介绍多态之前,我们先看看什么叫方法重写。

方法重写

子类继承父类,会继承父类的所有方法,当父类方法无法满足需求,可在子类中定义一个同名方法覆盖父类的方法,这就叫方法重写。当子类的实例调用该方法时,优先调用子类自身定义的方法,因为它被重写了。
例如:

class People:
    def speak(self):
        print("people is speaking")
class Student(People):
    #方法重写。重写父类的speak方法
    def speak(self):
        print("student is speaking")    
class Teacher(People):
    pass

#Student类的实例s
s = Student()
s.speak()
#Teacher类的实例t
t = Teacher()
t.speak()

输出结果:

student is speaking
people is speaking

因为子类Student重写了父类People的speak()方法,当Student类的对象s调用speak()方法,优先调用Student的speak方法,而Teacher()类没有重写People的speak方法,所以会t.speak()调用父类的speak()方法,打印people is speaking

多态特性

多态意味着变量并不知道引用的对象是什么,根据引用对象的不同表现不同的行为方式。
例如:

#代码块A。定义Animal类,Dog类,Cat类
class Animal:
    def eat(self):
        print("animal is eatting")
class Dog(Animal):
    def eat(self):
        print("dog is eatting")
class Cat(Animal):
    def eat(self):
        print("cat is eatting")

#代码块B。定义eatting_double方法,参数为Animal类型
def eatting_double(animal):
    animal.eat()
    animal.eat()

#代码块C。代码执行区,相当于main方法。
animal = Animal()
dog = Dog()
cat = Cat()

eatting_double(animal)
eatting_double(dog)  #接收的参数必须是拥有eat方法的对象,否则执行报错
eatting_double(cat)

输出结果:

animal is eatting
animal is eatting
dog is eatting
dog is eatting
cat is eatting
cat is eatting

上述代码中,Dog类继承自Animal类,重写了Animal的eat法。代码块B定义了eatting_double法,代码块C调用了该方法,多态的特性可以使得当我们再定义一个新的Animal子类——Cat类时,不需要修改eatting_double法的方法体,同样可以通过eatting_double(cat)来调用tiger的eat法,只需要Cat类正确地定义eat方法。

总结

子类继承父类,可以继承父类的所有方法,当父类的方法不满足需求时,还可以重写父类的方法,只需方法名称和基类的方法名称保持相同即可,另外子类还能定义自己特有的方法。