- # 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)
- #该片段来自于http://www.codesnippet.cn/detail/2207201513207.html
来源: http://www.codesnippet.cn/detail/2207201513207.html