Friday, October 2, 2015

Python polymorphism

Note
http://stackoverflow.com/questions/3724110/practical-example-of-polymorphism

Example:

#__author__ = 'valli_000'


class Animal(object):
    def __init__(self, Animalname):
        self.Animalname = Animalname

    def talk(self):
        pass


class Dog(Animal):
    def __init__(self, Animalname):
        super(self.__class__, self).__init__(Animalname)

    def talk(self):
        print "Sound of Animal " + self.Animalname + " is Bow Bow !"


class cat(Animal):
    def __init__(self, Animalname):
        super(self.__class__, self).__init__(Animalname)

    def talk(self):
        print "Sound of Animal " + self.Animalname + " is Meow Meow !"


x = cat("Pet 1")
x.talk()

y = Dog("Pet 2")
y.talk()


output:
C:\Python27\python.exe C:/Users/valli_000/PycharmProjects/Selflearning/Polymorphism.py

Sound of Animal Pet 1 is Meow Meow !
Sound of Animal Pet 2 is Bow Bow !

Process finished with exit code 0

No comments:

Post a Comment