2

我正在阅读 Effective Python 书,我找到了以下代码

class MyBaseClass(object):
    def __init__(self, value):
        self.value = value
        print "I changed it   to MyBaseClass",self.value

class TimesFiveCorrect(MyBaseClass):
    def __init__(self, value):
        super(TimesFiveCorrect, self).__init__(value)
        self.value *= 5
        print "I changed it   to TimesFiveCorrect ",self.value

class PlusTwoCorrect(MyBaseClass):
    def __init__(self, value):
        super(PlusTwoCorrect, self).__init__(value)
        self.value += 2
        print "I changed it   to PlusTwoCorrect ",self.value

class Factor(TimesFiveCorrect, PlusTwoCorrect):
    def  __init__(self, value):
        super(Factor, self).__init__(value)
        print "I changed it   to Factor ",self.value

foo = Factor(5)
from pprint import  pprint
pprint(Factor.mro())

我期望 foo 的值是27( 5 * 5 + 2)。但事实证明是35。输出如下

I changed it   to MyBaseClass 5
I changed it   to PlusTwoCorrect  7
I changed it   to TimesFiveCorrect  35
I changed it   to Factor  35
[<class '__main__.Factor'>,
 <class '__main__.TimesFiveCorrect'>,
 <class '__main__.PlusTwoCorrect'>,
 <class '__main__.MyBaseClass'>,
 <type 'object'>]

我可以理解MRO,但我没有得到执行命令……不应该TimesFiveCorrect先调用吗?

4

1 回答 1

2

但是 MRO 是执行顺序,您的打印输出解释了正在发生的事情。

TimesFiveCorrect 首先调用。但是,它做的第一件事是调用 super 方法,该方法解析为 PlusTwoCorrect;然后调用它的超级方法,该方法解析为 MyBaseClass。只有当这些方法都返回时,值才会发生变化并且打印语句才会发生。

如果您想要 27 的结果,您可以将super()调用移到每个方法的末尾。在调用超级方法之前,突变和打印将首先发生。

于 2016-05-09T14:26:35.263 回答