问题描述:

This question already has an answer here:

  • Method Resolution Order in case of Base Classes Having different init params

    5 answers

网友答案:

Take a look at print respbarry.mro() output:

[<class '__main__.respbarry'>, <class '__main__.computer'>, <class '__main__.laptop'>, <class '__main__.machine'>, <type 'object'>]

In multiple inheritance after linerization super(computer,self).__init__(...) will call laptop constructor. That's why you get this error.

That is a feature of Python which allows to change the behavior of an object adding a new class into inheritance chain.

Take a look at https://www.reddit.com/r/Python/comments/335045/raymond_hettinger_super_considered_super_pycon/

网友答案:

If you are passing different parameters to a method being called via super, all the implementations of that method going up the MRO towards object() need to have compatible signatures. The __init__ method is no exception. Add an additional **kwargs parameter to each of your base class constructors and that error will disappear.

The definition of the machine class should look like this:

class machine(object):
    def __init__(self, processor, **kwargs):
        print "I am in constructor of machine class"
        print processor


class computer(machine):
    def __init__(self, name, processor):
        print "I am in constructor of computer class"
        super(computer,self).__init__(name=name, processor=processor)
        print name,
        print processor


class laptop(machine):
    def __init__(self, name, processor):
        print "I am in constructor of laptop class"
        super(laptop,self).__init__(name=name, processor=processor)
        print name,
        print processor

class respbarry(computer,laptop):
    def __init__(self, name, processor):
        print "I am in constructor of respbarry class"
        super(respbarry,self).__init__(name=name,processor=processor)
        print name,
        print processor
相关阅读:
Top