Python object-oriented features - polymorphism (basic concepts, code examples)

python old bird 2022-09-23 08:05:15 阅读数:805

pythonobject-orientedobjectorientedfeatures

欢迎关注博主 python老鸟 或 前往 『Python自学网』, 从基础入门免费课程开始,逐步深入学习python全栈体系课程,适合新手入门到精通全栈开发.


免费专栏传送门:《Python基础教程


一、面向对象三大特征:

1)封装: 根据职责将属性和方法封装到一个抽象的类中

  1. 定义类的准则

2)继承: Inheritance enables code reuse,相同的代码不需要重复的编写

  1. 设计类的技巧
  2. Subclasses target their own unique needs,编写特定的代码

3)多态:不同的子类对象调用相同的父类方法,产生不同的执行结果

  1. Polymorphism can increase the flexibility of code pairs
  2. 以继承和重写父类方法为前提
  3. 是调用方法的技巧,不会影响到类的内部设计

二、多态案例演练:

需求:

1.在Dog类中封装方法game

Ordinary dogs simply play

2.定义XiaoTianQuan继承自Dog,并且重写game方法

XiaoTianQuanand play in the sky

3.定义person类,并且封装一个和狗玩的方法

在方法内部,直接让狗对象调用game方法

部分代码:

class Dog(object):
def __init__(self, name):
self.name = name
def game(self):
print("%s play normally----" % self.name)
class XiaoTianQuan(Dog):
def game(self):
print("%s play in heaven----" % self.name)
class Person(object):
def __init__(self, name):
self.name = name
def game_with_dog(self, dog):
print("%s 和 %s 开心玩耍" % (self.name, dog.name))
# 让狗玩耍
dog.game()
# 1. 创建狗对象
xiaobai = Dog("小白")
# 2. 创建小夏对象
xiaoxia = Person("小夏")
# 3. Let Xiaoxia call the method of playing with the dog
xiaoxia.game_with_dog(xiaobai)

执行结果:

Continue to the next code:

Comment out the common noob

# xiaobai = Dog("小白")

Add flying whites,XiaoTianQuanThe class creates another small white object ,其他代码不变

xiaobai = XiaoTianQuan("Flying little white")

The modified part and the execution result are shown in the figure:

案例总结:

Person类中只需要让狗对象调用game方法,It doesn't matter what kind of dog it is,因为game方法是在Dog父类中定义的,在程序执行时,传入不同的狗对象实参,就会产生不同的执行效果.

copyright:author[python old bird],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/266/202209230724062509.html