The polymorphism of the 3 major characteristics of Python object-oriented

Polymorphism is to call the same method on different objects to produce different execution results.

Polymorphism can increase the flexibility of the code. It is a technique to call methods on the premise of inheriting and overriding the parent class method and will not affect the internal design of the class.

We all know that Python is a weakly typed language, and its most obvious feature is that when variables are used, there is no need to specify specific data types for them.

Example:

The method game is encapsulated in the Dog class, and ordinary dogs simply play.

Define XiaoTianDog inherited from Dog, and rewrite the game method, the snarling dog needs to play in the sky.

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.

Polymorphism

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)
# 小明 和 飞天旺财 快乐的玩耍...
# 飞天旺财 飞到天上去玩耍...

The game method is defined in the Dog parent class. In the Person class, only the dog object needs to call the game method, regardless of the specific dog.

When the program is executed, passing in different dog object actual parameters will produce different execution effects.

The polymorphic characteristics of a class must meet the following two prerequisites:

  • Inheritance: Polymorphism must occur between the child class and the parent class.
  • Rewrite: The subclass rewrites the method of the parent class.

Polymorphism makes it easier to write universal code and make universal programs to adapt to changing needs!


The pilgrimage of programming

Guess you like

Origin blog.csdn.net/beyondamos/article/details/108272391