Python学习札记(三十八) 面向对象编程 Object Oriented Program 9
2017-03-05 22:21
666 查看
参考:多重继承
NOTE
#!/usr/bin/env python3 class Animal(object): def __init__(self, name): self.name = name def getname(self): print(self.name) class Fly(object): def __init__(self): pass def getfly(self): print('could fly') class Bird(Animal, Fly): pass def main(): b = Bird('bird') b.getname() b.getfly() if __name__ == '__main__': main()
sh-3.2# ./oop10.py bird could fly
通过多重继承,一个子类就可以同时获得多个父类的所有功能。
1.MixIn
一般来说,继承的关系是主线单一继承下来的,如:
Animal -> Bird -> Bat
但是如果要加入其它额外的属性和方法,可以通过多重继承来实现,这种方式称为MixIn。
MixIn的目的就是给一个类增加多个功能,这样,在设计类的时候,我们优先考虑通过多重继承来组合多个MixIn的功能,而不是设计多层次的复杂的继承关系。
2.Python自带的很多库也使用了MixIn。
举个例子,Python自带了TCPServer和UDPServer这两类网络服务,而要同时服务多个用户就必须使用多进程或多线程模型,这两种模型由ForkingMixIn和ThreadingMixIn提供。通过组合,我们就可以创造出合适的服务来。
2017/3/5
相关文章推荐
- Python学习札记(三十四) 面向对象编程 Object Oriented Program 5
- Python学习札记(三十) 面向对象编程 Object Oriented Program 1
- Python学习札记(三十三) 面向对象编程 Object Oriented Program 4
- Python学习札记(三十七) 面向对象编程 Object Oriented Program 8 @property
- Python学习札记(三十五) 面向对象编程 Object Oriented Program 6
- Python学习笔记09_面向对象编程Object Oriented Programming
- Python学习札记(三十一) 面向对象编程 Object Oriented Program 2
- Python学习札记(三十六) 面向对象编程 Object Oriented Program 7 __slots__
- Python学习札记(三十二) 面向对象编程 Object Oriented Program 3
- Python学习札记(三十九) 面向对象编程 Object Oriented Program 10
- Python面向对象编程(Object-Oriented)和装饰器(decorator)
- Python学习札记(四十) 面向对象编程 Object Oriented Program 11
- Python Object Oriented Programming (面向对象编程) Generator
- Python学习 面向对象编程
- 面向对象编程(Object Oriented Programming)概念总结及延伸(一)
- Files and Strings(Chapter 10 of Python 3 Object Oriented Programming)
- 面向对象编程(Object Oriented Programming)概念及延伸(三)
- 面向对象编程(Object Oriented Programming)概念及延伸(二)
- When Objects are Alike(Chapter 3 of Python 3 Object Oriented Programming)
- Python3 Object Oriented Programming notes