Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
67 lines (41 loc) · 1.8 KB

File metadata and controls

67 lines (41 loc) · 1.8 KB
Copy raw file
Download raw file
Edit and raw actions

六、类的多态

多态的概念其实不难理解,它是指对不同类型的变量进行相同的操作,它会根据对象(或类)类型的不同而表现出不同的行为。

事实上,我们经常用到多态的性质,比如:

>>> 1 + 2
3
>>> 'a' + 'b'
'ab'

可以看到,我们对两个整数进行 + 操作,会返回它们的和,对两个字符进行相同的 + 操作,会返回拼接后的字符串。也就是说,不同类型的对象对同一消息会作出不同的响应。

看下面的实例,来了解多态:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

class User(object):
    def __init__(self, name):
        self.name = name

    def printUser(self):
        print('Hello !' + self.name)


class UserVip(User):
    def printUser(self):
        print('Hello ! 尊敬的Vip用户:' + self.name)


class UserGeneral(User):
    def printUser(self):
        print('Hello ! 尊敬的用户:' + self.name)


def printUserInfo(user):
    user.printUser()


if __name__ == '__main__':
    userVip = UserVip('两点水')
    printUserInfo(userVip)
    userGeneral = UserGeneral('水水水')
    printUserInfo(userGeneral)

输出的结果:

Hello ! 尊敬的Vip用户:两点水
Hello ! 尊敬的用户:水水水

可以看到,userVip 和 userGeneral 是两个不同的对象,对它们调用 printUserInfo 方法,它们会自动调用实际类型的 printUser 方法,作出不同的响应。这就是多态的魅力。

要注意喔,有了继承,才有了多态,也会有不同类的对象对同一消息会作出不同的相应。

最后,本章的所有代码都可以在 https://github.com/TwoWater/Python 上面找到,文章的内容和源文件都放在上面。同步更新到 Gitbooks。

Morty Proxy This is a proxified and sanitized view of the page, visit original site.