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
>>> 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.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
2023-07-31 Go - go.work, go.mod, go.sum
2023-07-31 Go - installation
2023-07-31 Go - env
2023-07-31 Python - match case