python 2.7.13 中如何使用 super() 调用 base class 函数?

How to use super() to call base class function in python 2.7.13?

我有一个多级继承 (A->B->C)。在基础 class 中,我有一个名为 "my_dict" 的字典变量。从派生 class,我通过 super().add_to_dict() 调用基础 class 函数来添加一些值。

以下代码在 python 3.7 中按预期工作。但是在 Python 2.7.13 中它会抛出错误。有人可以帮我修复 2.7.13 吗?

from collections import OrderedDict

class A():
    def __init__(self):
        self.my_dict = OrderedDict()
    def add_to_dict(self):
        self.my_dict["zero"]=0
        self.my_dict["one"]=1 


class B(A):
    def add_to_dict(self):
        super().add_to_dict()
        self.my_dict["two"]=2
    def print_dict(self):
        print("class B {}".format(my_dict))


class C(B):
    def add_to_dict(self):
        super().add_to_dict()
        self.my_dict["three"]=3
    def print_dict(self):
        print("class C {}".format(self.my_dict))
obj = C()
obj.add_to_dict()
obj.print_dict()

Output ( 2.7.13):

File "test.py", line 15, in add_to_dict super().add_to_dict()

TypeError: super() takes at least 1 argument (0 given)

输出 (python 3.7)

class C OrderedDict([('zero', 0), ('one', 1), ('two', 2), ('three' , 3)])

在py2中你可以使用super(<Class>, <instance>).<function>()。这些也必须是 "new style" 类。这些是通过从 object.

继承来定义的

所以在你的情况下正确的代码应该是:

class A(object):
    def __init__(self):
        self.my_dict = OrderedDict()
    def add_to_dict(self):
        self.my_dict["zero"]=0
        self.my_dict["one"]=1


class B(A):
    def add_to_dict(self):
        super(B, self).add_to_dict()
        self.my_dict["two"]=2
    def print_dict(self):
        print("class B {}".format(my_dict))


class C(B):
    def add_to_dict(self):
        super(C, self).add_to_dict()
        self.my_dict["three"]=3
    def print_dict(self):
        print("class C {}".format(self.my_dict))