python 27 super继承(解决多重继承时,老办法init父类多次的问题)
2017-12-04 18:13
866 查看
http://blog.csdn.net/abe_abd/article/details/52450354
http://blog.csdn.net/qq_16949707/article/details/72625219
一 Python类分为两种,一种叫经典类,一种叫新式类。两种都支持多继承。
考虑一种情形,B继承于A,C继承于A和B, 但C需要调用父类的init()函数时,前者会导致父类A的init()函数被调用2次,这是不希望看到的。而且子类要显式地指定父类,不符合DRY原则。1 普通继承
# 经典类 class A(): def __init__(self): print 'A' class B(A): def __init__(self): A.__init__(self) print 'B' class C(B, A): def __init__(self): A.__init__(self) B.__init__(self) print 'C' if __name__=='__main__': C_Child = C()1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
A A B C1
2
3
4
5
这里A被init了俩次,不符合DRY?规则
2 super继承
采用新式类,要求最顶层的父类一定要继承于object,这样就可以利用super()函数来调用父类的init()等函数,每个父类都执行且执行一次,并不会出现重复调用的情况。而且在子类的实现中,不用到处写出所有的父类名字,符合DRY原则。# 新式类 class A(object): def __init__(self): print 'A' class B(A): def __init__(self): super(B, self).__init__() print 'B' class C(B, A): def __init__(self): super(C, self).__init__() print 'C' if __name__=='__main__': C_Child = C()1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
A B C1
2
3
4
采用super()方式时,会自动找到第一个多继承中的第一个父类,但是如果还想强制调用其他父类的init()函数或两个父类的同名函数时,就要用老办法了。
class Person(object): name = "" sex = "" def __init__(self, name, sex='U'): print 'Person' self.name=name self.sex=sex class Consumer(object): def __init__(self): print 'Consumer' class Student(Person, Consumer): def __init__(self, score,name): print Student.__bases__ super(Student, self).__init__(name, sex='F') Consumer.__init__(self) self.score=score s1 = Student(90, 'abc') print s1.name, s1.score, s1.sex1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
(<class '__main__.Person'>, <class '__main__.Consumer'>) Person Consumer abc 90 F1
2
3
4
5
这里肯定得用老办法啊,不属于多重继承了吧??
参考:
http://www.jackyshen.com/2015/08/19/multi-inheritance-with-super-in-Python/
相关文章推荐
- python 27 super继承(解决多重继承时,老办法init父类多次的问题)
- Python多重继承引发的问题——牛逼的super
- [置顶] python入门:类的多重继承问题、重写、未绑定的超类方法、super()
- 深入super,看Python如何解决钻石继承难题 【转】
- python MySQLdb在windows环境下的安装、出错问题以及解决办法
- Python安装模块(numpy等)问题的两种解决办法——常规方法和Anaconda
- python继承中super的问题
- 在Python中TypeError: object() takes no parameters新手问题的解决办法
- Python随笔之CSRF问题解决办法
- Python类的多重继承问题深入分析
- python3.2打开utf8的txt文件时BOM问题的解决办法
- 解决python27 matplotlib 中文不显示问题
- 【Python】Python3 多继承的super init()问题
- 贴一下今天python中文乱码问题解决办法。
- python2.7 使用super关键词 报错 TypeError: must be type, not classobj 解决办法
- python读文件读到windows休止符的问题及解决办法
- python问题Non-ASCII character '\xe5' in file Apriori.py on line 1, but no encoding declared 解决办法
- Python中str is not callable问题详解及解决办法
- 安装常见python包,出现的问题,及其解决的办法
- Problem B. Investing at the Market 问题B 市场投资 解决办法 Python方法