Python:多态

多态

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

方法重写

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

 
  1. class People:
  2. def speak(self):
  3. print("people is speaking")
  4. class Student(People):
  5. #方法重写。重写父类的speak方法
  6. def speak(self):
  7. print("student is speaking")
  8. class Teacher(People):
  9. pass
  10.  
  11. #Student类的实例s
  12. s = Student()
  13. s.speak()
  14. #Teacher类的实例t
  15. t = Teacher()
  16. t.speak()

Python

输出结果:

student is speaking
people is speaking

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

多态特性

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

 
  1. #代码块A。定义Animal类,Dog类,Cat类
  2. class Animal:
  3. def eat(self):
  4. print("animal is eatting")
  5. class Dog(Animal):
  6. def eat(self):
  7. print("dog is eatting")
  8. class Cat(Animal):
  9. def eat(self):
  10. print("cat is eatting")
  11.  
  12. #代码块B。定义eatting_double方法,参数为Animal类型
  13. def eatting_double(animal):
  14. animal.eat()
  15. animal.eat()
  16.  
  17. #代码块C。代码执行区,相当于main方法。
  18. animal = Animal()
  19. dog = Dog()
  20. cat = Cat()
  21.  
  22. eatting_double(animal)
  23. eatting_double(dog) #接收的参数必须是拥有eat方法的对象,否则执行报错
  24. eatting_double(cat)

Python

输出结果:

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方法。

总结

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值