Python object-oriented polymorphism (4)

Polymorphism

aims

  • Polymorphism

Three object-oriented features

  • Encapsulation Encapsulates attributes and methods into an abstract class according to responsibilities
    1. Guidelines for defining classes
  • Inheritance to achieve code reuse, the same code does not need to be repetitively written
    1. Skills for designing classes
    2. Subclasses write specific codes for their own unique needs
  • Different subclass objects of polymorphism call the same parent method and produce different execution results.
    1. Polymorphism can increase the flexibility of the code.
    2. It is premised on inheriting and rewriting the parent class method.
    3. It is the technique of calling methods. Will affect the internal design of the class
    Insert picture description here

Polymorphic case walkthrough

Requirements
1. Encapsulate the method game in the Dog class

Ordinary dogs just simply play

2. Define XiaoTianDog to inherit from Dog, and rewrite the game method

The snarling dog needs to play in the sky

3. Define the Person class and encapsulate a method to play with the dog

Inside the method, let the dog object call the game method directly
Insert picture description here

Case summary

  • In the Person class, only the dog object needs to call the game method, and does not care what the dog
    game method is defined in the Dog parent class
  • When the program is executed, passing in different dog object actual parameters will produce different execution effects

Polymorphism makes it easier to write general code and make general programming to adapt to changing needs!

class Dog(object):def __init__(self, name):
       self.name = name
​
   def game(self):
       print("%s 蹦蹦跳跳的玩耍..." % self.name)
​
​
class XiaoTianDog(Dog):def game(self):
       print("%s 飞到天上去玩耍..." % 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. 创建一个狗对象
# wangcai = Dog("旺财")
wangcai = XiaoTianDog("飞天旺财")# 2. 创建一个小明对象
xiaoming = Person("小明")# 3. 让小明调用和狗玩的方法
xiaoming.game_with_dog(wangcai)  

Guess you like

Origin blog.csdn.net/weixin_42272869/article/details/113486775