多态实例-一种接口,多种实现

class animal(object):
    def __init__(self,name):
        self.name=name
    def talk(self):
        pass

class Cat(animal):
    def talk(self):
        print("Mou,Mou")
class Dog(animal):
    def talk(self):
        print("Wang Wang------")
c1=Cat("机器猫")
c1.talk()

d1=Dog("苯笨")
d1.talk()

def Animal_talk(obj):
    obj.talk()
Animal_talk(c1)
Animal_talk(d1)

 

改良版:

 

class animal(object):
    def __init__(self,name):
        self.name=name
    def talk(self):
        pass
    @staticmethod
    def animal_talk(obj):
        obj.talk()

class Cat(animal):
    def talk(self):
        print("Mou,Mou")
class Dog(animal):
    def talk(self):
        print("Wang Wang------")
c1=Cat("机器猫")
c1.talk()

d1=Dog("苯笨")
d1.talk()

animal.animal_talk(c1)
animal.animal_talk(d1)

 运行结果:

Mou,Mou
Wang Wang------
Mou,Mou
Wang Wang------

 

posted on 2017-07-29 16:44  momo8238  阅读(218)  评论(0编辑  收藏  举报