Python study notes (12): object-oriented polymorphism

1. Definition of polymorphism

When the same variable is calling the same method, it is entirely possible to exhibit multiple behaviors (the specific behavior is determined by the object referenced by the variable), which is called polymorphism.

2. Examples of polymorphism

As follows:

# 定义一个Animal类
class Animal(object):
    def __init__(self, species, color):
        self.species = species
        self.color = color

# 定义一个子类Dog
class Dog(Animal):
    def speak(self):
        print("我是一只{},我的颜色是{}".format(self.species, self.color))

# 定义一个子类Cat
class Cat(Animal):
    def speak(self):
        print("我是一只{},我的颜色是{}".format(self.species, self.color))

# 实例化一个Dog类对象
animal = Dog("泰迪", "棕色")
animal.speak()

# 实例化一个Cat类对象
animal = Cat("波斯猫", "白色")
animal.speak()

The output is as follows:

我是一只泰迪,我的颜色是棕色
我是一只波斯猫,我的颜色是白色

It can be seen from the above running results that when the same variable animal calls the same method speak(), because the objects pointed to by the animal are different, it exhibits different behavior characteristics, which is polymorphism.

The above code can be modified as follows:

# 定义一个Animal类
class Animal(object):
    def __init__(self, species, color):
        self.species = species
        self.color = color

# 定义一个子类Dog
class Dog(Animal):
    def speak(self):
        print("我是一只{},我的颜色是{}".format(self.species, self.color))

# 定义一个子类Cat
class Cat(Animal):
    def speak(self):
        print("我是一只{},我的颜色是{}".format(self.species, self.color))

# 实例化一个Dog类对象
teddy = Dog("泰迪", "棕色")
# 实例化一个Cat类对象
persian_cat = Cat("波斯猫", "白色")

# 定义一个统一的接口来访问
def func(object):
    object.speak()

func(teddy)
func(persian_cat)

 

Guess you like

Origin blog.csdn.net/weixin_44679832/article/details/114381401