
多态
class Person(): def eat(self): print('人吃五谷杂粮') class Cat(): def eat(self): print('猫吃鱼') class Dog(): def eat(self): print('狗啃骨头') #这三个类都有一个同名方法,eat #编写函数 def fun(obj): #obj是函数的形式参数,在定义处知道之歌形参的数据类型吗? obj.eat() #通过变量obj(对象)调用eat的方法 #创建三个类的对象 per=Person() cat=Cat() dog=Dog() #调用fun函数 fun(per) #python中的多态,不关心对象的数据类型,只关心对象是否具有同名方法 fun(cat) fun(dog)
输出
人吃五谷杂粮猫吃鱼狗啃骨头

(仅供参考)
Comments NOTHING