【发布时间】:2020-04-06 14:31:09
【问题描述】:
我有一个多级继承 (A->B->C)。在基类中,我有一个名为“my_dict”的字典变量。从派生类中,我通过 super().add_to_dict() 调用基类函数来添加一些值。
以下代码在 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()
输出(2.7.13):
文件“test.py”,第 15 行,在 add_to_dict 中 super().add_to_dict()
TypeError: super() 至少需要 1 个参数(给定 0)
输出(python 3.7)
C 类 OrderedDict([('zero', 0), ('one', 1), ('two', 2), ('three', 3)])
【问题讨论】:
-
这能回答你的问题吗? super in python 2.7
标签: python inheritance super