2013年7月5日 星期五

python Polymorphism (standard, python)

python sample Polymorphism  


class Fruit:
    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 Apple(Fruit):
    def talk(self):
        return 'Red!'

class Orange(Fruit):
    def talk(self):
        return 'orangeColor! orangeColor!'

Fruits = [Apple('Missy'),
           Orange('Lassie')]

for Fruit in Fruits:
    print(Fruit.name + ': ' + Fruit.talk())


# prints the following:
# Missy: Red!
# Lassie: orangeColor! orangeColor!

沒有留言:

張貼留言