Python的super解释
Python的super解释
shawnplaying 发表于1年前
Python的super解释
• 发表于 1年前
• 阅读 8
• 收藏 0
• 评论 0

``````class MyBaseClass(object):
def __init__(self, value):
self.value = value

class MyChildClass(MyBaseClass):
def __init__(self):
MyBaseClass.__init__(self, 5)``````

``````class TimesTwo(object):
def __init__(self):
self.value *= 2

class PlusFive(object):
def __init__(self):
self.value += 5``````

``````class OneWay(MyBaseClass, TimesTwo, PlusFive):
def __init__(self, value):
MyBaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)``````

``````foo = OneWay(5)
print('First ordering is (5 * 2) + 5 =', foo.value)

>>>
First ordering is (5 * 2) + 5 = 15``````

``````class AnotherWay(MyBaseClass, PlusFive, TimesTwo):
def __init__(self, value):
MyBaseClass.__init__(self, value)
TimesTwo.__init__(self)
PlusFive.__init__(self)``````

``````bar = AnotherWay(5)
print('Second ordering still is', bar.value)

>>>
Second ordering still is 15``````

``````class TimesFive(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value *= 5

class PlusTwo(MyBaseClass):
def __init__(self, value):
MyBaseClass.__init__(self, value)
self.value += 2``````

``````class ThisWay(TimesFive, PlusTwo):
def __init__(self, value):
TimesFive.__init__(self, value)
PlusTwo.__init__(self, value)``````

``````foo = ThisWay(5)
print('Should be (5 * 5) + 2 = 27 but is', foo.value)
>>>
Should be (5 * 5) + 2 = 27 but is 7``````

``````# Python2
class TimesFiveCorrect(MyBaseClass):
def __init__(self, value):
super(TimesFiveCorrect, self).__init__(value)
self.value *= 5

class PlusTwoCorrect(MyBaseClass):
def __init__(self, value):
super(PlusTwoCorrect, self).__init__(value)
self.value += 2``````

``````# Python 2
class GoodWay(TimesFiveCorrect, PlusTwoCorrect):
def __init__(self, value):
super(GoodWay, self).__init__(value)

foo = GoodWay(5)
print 'Should be 5 * (5 + 2) = 35 and is', foo.value
>>>
Should be 5 * (5 + 2) = 35 and is 35``````

``````from pprint import pprint
pprint(GoodWay.mro())
>>>
[<class '__main__.GoodWay'>,
<class '__main__.TimesFiveCorrect'>,
<class '__main__.PlusTwoCorrect'>,
<class '__main__.MyBaseClass'>,
<class 'object'>]``````

1. `super`语句有些麻烦, 必须指定所在的类, `self`对象, 构造方法名(通常是`__init__`)以及所有的参数值.

2. 调用`super`时, 必须写出当前类的名称, 但是类的名称很可能会更改, 那么每一条`super`语句也就必须要更改.

``````class Explicit(MyBaseClass):
def __init__(self, value):
super(__class__, self).__init__(value * 2)

class Implicit(MyBaseClass):
def __init__(self, value):
super().__init__(value * 2)

assert Explicit(10).value == Implicit(10).value``````

### 小结

1. Python使用MRO来解决父类初始化顺序及菱形继承问题;

2. 应该使用内置的`super`函数来初始化父类.

1. Slatkin, Brett. Effective Python: 59 Specific Ways to Write Better Python. Pearson Education, 2015.

2. Brett Slatkin, 爱飞翔. Effective Python: 编写高质量Python代码的59个有效 方法. 机械工业出版社, 2016.1.

×