【问题标题】:How to use super() to call base class function in python 2.7.13? [duplicate]python 2.7.13中如何使用super()调用基类函数? [复制]
【发布时间】: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)])

【问题讨论】:

标签: python inheritance super


【解决方案1】:

在 py2 中你可以使用super(<Class>, <instance>).<function>()。这些也必须是“新风格”课程。这些是通过从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))

【讨论】:

  • 我试过了,但是得到了这个错误:“TypeError: super() argument 1 must be type, not classobj”
  • @utek 。谢谢我错过了新类型的对象。 A类(对象)::)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-23
  • 2019-12-24
  • 1970-01-01
  • 2013-06-23
  • 2017-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多