The concept of polymorphism is actually not difficult to understand. It refers to performing the same operation on variables of different types, and it will show different behaviors depending on the type of object (or class).
In fact, we often use polymorphic properties, such as:
>>> 1 + 2 3 >>> 'a' + 'b' 'ab'
As you can see, when we operate on two integers, their sum will be returned, and on two characters The same operation will return the concatenated string. That is, objects of different types will respond differently to the same message.
Look at the following example to understand polymorphism:
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- class User(object): def __init__(self, name): self.name = name def printUser(self): print('Hello !' + self.name) class UserVip(User): def printUser(self): print('Hello ! 尊敬的Vip用户:' + self.name) class UserGeneral(User): def printUser(self): print('Hello ! 尊敬的用户:' + self.name) def printUserInfo(user): user.printUser() if __name__ == '__main__': userVip = UserVip('两点水') printUserInfo(userVip) userGeneral = UserGeneral('水水水') printUserInfo(userGeneral)
Output results:
Hello ! 尊敬的Vip用户:两点水 Hello ! 尊敬的用户:水水水
As you can see, userVip and userGeneral are two different objects. Calling the printUserInfo method, they will automatically call the printUser method of the actual type and respond differently. This is the beauty of polymorphism.
It should be noted that with inheritance, polymorphism is possible, and objects of different types will respond differently to the same message.
Next Section