美文网首页
5-2、类的继承与多态

5-2、类的继承与多态

作者: 1e026ca57a8e | 来源:发表于2020-05-19 10:08 被阅读0次
    # 继承中的多态度
    # ABCMeta就是让你的类变成一个纯虚类,子类必须实现某个方法,这个方法在父类中用@abc.abstractmethod修饰
    from abc import ABCMeta, abstractmethod
    
    
    class Pet(object, metaclass=ABCMeta):
        def __init__(self, nickname):
            self._nickname = nickname
    
        @abstractmethod
        def make_voice(self):
            pass
    
    
    class Dog(Pet):
        def make_voice(self):
            print('%s在汪汪汪' % self._nickname)
    
    
    class Sheep(Pet):
        def make_voice(self):
            print('%s在咩咩咩' % self._nickname)
    
    
    def main():
        pets = [Dog('dog'), Sheep('sheep')]
        for i in pets:
            i.make_voice()
    
    
    if __name__ == '__main__':
        main()
    
    

    相关文章

      网友评论

          本文标题:5-2、类的继承与多态

          本文链接:https://www.haomeiwen.com/subject/kgzuohtx.html