python_99_面向对象多态

#多态:一种接口,多种实现。主要作用:实现接口重用
#方法1:
class Animal(object):
    def __init__(self,name):
        self.name=name
class Cat(Animal):
    def talk(self):
        print('%s: 喵喵喵!' % self.name)
class Dog(Animal):
    def talk(self):
        print('%s: 汪!汪!汪!'% self.name)
def func(obj): #一个接口,多种形态
    obj.talk()
c1 = Cat('王')
d1 = Dog('齐')
func(c1)
func(d1)
#方法2
class Animal(object):
    def __init__(self,name):
        self.name=name
    @staticmethod
    def func(obj):  # 一个接口,多种形态
        obj.talk()
class Cat(Animal):
    def talk(self):
        print('%s: 喵喵喵!' % self.name)
class Dog(Animal):
    def talk(self):
        print('%s: 汪!汪!汪!'% self.name)

c1 = Cat('蒋鑫')
d1 = Dog('石')
Animal.func(c1)
Animal.func(d1)

 

posted @ 2018-02-26 12:04  耐烦不急  阅读(179)  评论(0编辑  收藏  举报