ZhangZhihui's Blog  

The three main features of object-oriented programming are - encapsulation, inheritance and polymorphism. We have seen the first two, now let us see what is polymorphism. The meaning of the word polymorphism is the ability to take many forms. In programming, this means the ability of code to take different forms depending on the type with which it is used. The behaviour of the code can depend on the context in which it is used. Let us understand this with the help of an example.

def do_something(x):
   x.move()
   x.stop()

We have this function do_something that has a parameter x. Inside this function, two methods are called on x. We know that Python is a dynamically typed language; there are no type declarations. The type of parameter x is not declared, we can send any type of object to this function. We could send a list object or a str object, but in that case, we will get error because str and list types do not support the methods move and stop. The function do_something will work correctly as long as we send objects of those types that support the two methods move and stop.

Next, we have defined three classes that have the methods move and stop. The implementation for these methods is different in each one of them.

class Car:
   def start(self):
       print('Engine started')

   def move(self):
       print('Car is running')

   def stop(self):
       print('Brakes applied')


class Clock:
   def move(self):
       print('Tick Tick Tick')

   def stop(self):
       print('Clock needles stopped')


class Person:
    def move(self):
        print('Person walking')

    def stop(self):
        print('Taking rest')

    def talk(self):
        print('Hello')

Let us create instance objects of these classes.

>>> car = Car()

>>> clock = Clock()

>>> person = Person()

We can send all these instance objects to the do_something function since all three of them support the move and stop functions.

>>> do_something(car)

Car is running

Brakes applied

>>> do_something(clock)

Tick Tick Tick

Clock needles stopped

>>> do_something(person)

Person walking

Taking rest

So, any object that supports the two operations move and stop can be sent to this function. The behaviour of move and stop depends on the type of the object that they are operating upon. This is polymorphism, the same code can take different forms. While executing the code of function do_something, interpreter does not care about the type of x; any object that supports the two methods move and stop will work regardless of its specific type. Python is not concerned about what an object is, it just needs to know what an object does.

 

posted on 2024-07-31 09:19  ZhangZhihuiAAA  阅读(4)  评论(0编辑  收藏  举报