python-类的多态的理解

了解多态

  多态指的是一类事物有多种形态

.定义:多态是一中使用对象的方式,更容易编写出通用的代码,做出通用的编程,一适应需求的不断变化

实现步骤:

  1.定义父类,并提供公共方法

  2.定义子类,并重写父类方法

  3.传递子类对象给调用者,可以看到子类执行的效果不同

#coding:utf-8
  2 class Dog(object):
  3     def work(self):
  4         print("")
  5 
  6 class Onedog(Dog):
  7     #重写父类方法
  8     def work(self):
  9         print("中国")
 10 
 11 class TwoDog(Dog):
 12     #重写父类方法
 13     def work(self):
 14         print("英国")
 15 
 16 class Person(object):
 17     def work_with_dog(self,dog):
 18         #传入不同的对象,执行不同的代码,即不同的work函数
 19         dog.work()
 20 
 21 a = Onedog()
 22 b = TwoDog()
 23 c = Person()
 24 
 25 c.work_with_dog(a)
 26 c.work_with_dog(b)
 27  #运行结果
中国
英国
                                                         
~                                         
笨鸟先飞
原文地址:https://www.cnblogs.com/zoutingrong/p/13693096.html