如何在多重继承下调用__init__?

时间:2013-12-04 10:14:57

标签: python

如何在客户

下调用Xls.__init__

如果我尝试super(Customer, self).__init__(arg)

但得到例外*** TypeError: object.__init__() takes no parameters

我猜它试图调用object的init()

那我该怎么办?感谢

class Xls():
    """docstring for Xls"""
    def __init__(self, xls_fname):
        super(Xls, self).__init__()
        self.xls_data = {} # Store the whole Excel Data

    def read_workbook(self, xls_fname):
        print("{0} called workbook".format(self.__class__))
        self.xls_name = xls_fname
        self.rd_bk = xlrd.open_workbook(xls_fname)

class Customer(object, Xls, xls_oper.ReadWrite):
    """docstring for Customer"""
    def __init__(self, arg):
        self.arg = arg
        self.read_workbook(arg)
        ap(self.xls_name)
        ap(self.xls_data)

2 个答案:

答案 0 :(得分:3)

您必须Xls继承object或完全遗漏object。通过使Customer继承自object,您将混合使用旧式和新式类层次结构,这种情况正在破坏。 super()在此处找到了object.__init__,而不是Xls.__init__

当您将object移至Xls时,它可以正常运行:

class Xls(object):
    # ...

class Customer(Xls, xls_oper.ReadWrite):
    # ...

如果您完全删除object,则无法使用super();直接命名基类:

class Xls():
    # ...
    def __init__(self, xls_fname):
        # no base classes, no need to call a super __init__
        self.xls_data = {} # Store the whole Excel Data

class Customer(Xls, xls_oper.ReadWrite):
    # ...
    def __init__(self, arg):
        # Call base class __init__ directly, pass in self explicitly
        Xls.__init__(self, arg)

答案 1 :(得分:-3)

__ init __不是构造函数 - 它是一个初始化函数。 显然,你想调用Xls init - 而Super,选择第一个父类 改为使用

Xls.__init__(self)