Python多态

Python多态教程

多态就是一种事物的多种体现形式,函数的重写 其实就是多态的一种体现,在 Python 中,多态指的是父类的引用指向子类的对象。

什么是多态性

多态性是指具有不同功能的 函数 可以使用相同的函数名,这样就可以用一个函数名调用不同内容的函数。

面向对象 方法中一般是这样表述多态性:向不同的对象发送同一条消息,不同的对象在接收时会产生不同的行为(即方法)。也就是说,每个对象可以用自己的方式去响应共同的消息。所谓消息,就是调用函数,不同的行为就是指不同的实现,即执行不同的函数。

Python多态的优点

增加了程序的灵活性:以不变应万变,不论对象千变万化,使用者都是同一种形式去调用。

增加了程序的可扩展性:即使是调用程序的对象变了,只要是继承自同一个父类,代码就不用做任何修改。

案例

Python多态

使用继承,实现多态

print("嗨客网(www.haicoder.net)") class Animal: def eat(self): print("I like eat anything") class Cat(Animal): def eat(self): print("I am a cat, and i just like eat finish") class Dog(Animal): def eat(self): print("I am a dog, and i just like eat bone") animal = Animal() animal.eat() animal = Cat() animal.eat() animal = Dog() animal.eat()

程序运行后,控制台输出如下:

102_python多态.png

我们首先定义了一个 Animal 类,Animal 类有一个 eat 方法,接着,定义了一个 Cat 类和一个 Dog 类,Cat 类和 Dog 类都继承自 Animal 类。

Animal 类有一个 eat 方法,同时,Cat 类和 Dog 类也都有一个跟 Animal 类一模一样的 eat 方法,最后,我们首先实例化了一个 Animal 类,并调用了 Animal 类实例 animal 的 eat 方法。

接着,我们又同时实例化了一个 Cat 类和一个 Dog 类,并且都赋值给了 animal 对象,最后,我们发现,通过实例化不同的 animal 对象,我们分别实现了调用了 Animal、Dog 和 Cat 三个类的 eat 方法。

这就是继承实现了多态,同一个对象,不同的实例化,调用相同的函数,实现了调用不同类的函数。

Python多态

给函数传递不同的参数,实现多态

print("嗨客网(www.haicoder.net)") class Animal: def eat(self, animal): animal.eat() class Cat(Animal): def eat(self): print("I am a cat, and i just like eat finish") class Dog(Animal): def eat(self): print("I am a dog, and i just like eat bone") cat = Cat() dog = Dog() animal = Animal() animal.eat(cat) animal.eat(dog)

程序运行后,控制台输出如下:

103_python多态.png

我们在 Animal 类里面定义了一个 eat 方法,eat 方法接受两个参数,一个 self,一个是 animal 类型的对象,在 eat 方法里,我们直接调用了 animal 类型的对象的 eat 方法。

接着,我们定义了一个 Cat 类和一个 Dog 类,并且 Cat 类和 Dog 类都各自定义了 eat 方法,最后,我们实例化了一个 Cat 对象、一个 Dog 对象和一个 Animal 对象。

最后,我们分别将 cat 和 dog 实例传进 Animal 实例,实现了同一个函数,调用了 cat 和 dog 实例的 eat 方法。

Python多态教程

多态就是一种事物的多种体现形式,函数的重写其实就是多态的一种体现,在 Python 中,多态指的是父类的引用指向子类的对象。