码迷,mamicode.com
首页 > 编程语言 > 详细

Python : Polymorphism

时间:2014-10-26 21:07:49      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:blog   io   for   div   on   log   bs   ef   as   

class Animal:
    def __init__(self, name):    # Constructor of the class
        self.name = name
    def talk(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self):
        return ‘Meow!‘

class Dog(Animal):
    def talk(self):
        return ‘Woof! Woof!‘

animals = [Cat(‘Missy‘),
           Cat(‘Mr. Mistoffelees‘),
           Dog(‘Lassie‘)]

for animal in animals:
    print animal.name + ‘: ‘ + animal.talk()

# prints the following:
#
# Missy: Meow!
# Mr. Mistoffelees: Meow!
# Lassie: Woof! Woof!

  

Python : Polymorphism

标签:blog   io   for   div   on   log   bs   ef   as   

原文地址:http://www.cnblogs.com/bittorrent/p/4052707.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!