加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python 多态实例

发布时间:2020-05-25 01:04:07 所属栏目:Python 来源:互联网
导读:python 多态实例

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

# coding:utf-8
"""
多态(英语:Polymorphism),是指面向对象程序运行时,相同的消息可能会送给多个不同的类之对象,
而系统可依据对象所属类,引发对应类的方法,而有不同的行为。
简单来说,所谓多态意指相同的消息给予不同的对象会引发不同的动作称之。
在面向对象程序设计中,多态一般指子类型多态(Subtype polymorphism)。

上面的定义有点让初学者费解,黄哥用“打开”这个动作来描述面向对象的多态。
"打开",可以是打开门,打开窗户,打开书等等。"打开"这个动作,碰到不同的对象门,窗户,书,有不同的行为模式。
这个就是多态。
本文由黄哥python培训,黄哥所写
黄哥python远程视频培训班
https://github.com/pythonpeixun/article/blob/master/index.md

黄哥python培训试看视频播放地址
https://github.com/pythonpeixun/article/blob/master/python_shiping.md
"""
# 例1


class Door(object):

    def open(self):
        print "打开门"


class Windows(object):

    def open(self):
        print "打开窗户"


class Book(object):

    def open(self):
        print "打开书"

lst = [Door(),Windows(),Book()]

for item in lst:
    item.open()

# 例2 一般用继承来说明多态的例子


class Animal:

    def __init__(self,name):
        self.name = name

    def talk(self):
        raise NotImplementedError("Subclass must implement abstract method")


class Cat(Animal):

    def talk(self):
        return 'Meow!'


class Dog(Animal):

    def talk(self):
        return 'Woof! Woof!'

animals = [Cat('Missy'),Cat('Mr. Mistoffelees'),Dog('Lassie')]

for animal in animals:
    print animal.name + ': ' + animal.talk()

# 例3 python 内置有很多多态的应用
# 同样的 +号 可以用在不同的对象相加,体现(相仿:指相加这个事情)了多态的功能。
print 1 + 2
print "hello" + '黄哥'

# len 函数传不同的参数,也体现了多态的功能。
print len("黄哥python培训")
print len([2,4,5,7])

# 工程应用
# 一个简单的日志记录函数,用判断实现的,重构为面向对象多态来实现。
#如果有大量的判断语句,就可以用多态来实现。


def log_msg(log_type):
    msg = 'Operation successful'
    if log_type == 'file':
        log_file.write(msg)
    elif log_type == 'database':
        cursor.execute('INSERT INTO log_table (MSG) VALUES ('?')',msg)

#重构


class FileLogger(object):

    def log(self,msg):
        log_file.write(msg)


class DbLogger(object):

    def log(self,msg):
        cursor.execute('INSERT INTO log_table (MSG) VALUES ('?')',msg)


def log_msg(obj):
    msg = 'Operation successful'
    obj.log(msg)

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读