Question

For an amusing (and valid but unrelated) reason I want to do the following:

class Head(type, tuple):
    pass

But this results in

TypeError: multiple bases have instance lay-out conflict

(on python3.3 and python2.7)

Any way around this?

For the curious I want to create something that behaves like Mathematica expression (Derivative[1][g][x] being g'(x)). I know there are other ways, but for educational purposes I insist on this one.

Was it helpful?

Solution

I can't seem to find an appropriate link to it, but the point is that Python doesn't support multiple inheritence of several built-in types. You can't create a class that inherit both from "type" and "tuple", or from "int" and "str", or most other combinations. There is a mostly internal reason related to the internal layout of the instances: an "int" object's memory layout contains storage for the integer value; but this is incomptible with the layout of a "str" object, which contains storage for the characters. It's not possible to create an instance of a class that would inherit from both, because we don't know which memory layout it should have.

Compare this with the memory layout of an instance of a class that inherits only from object, directly or indirectly. Such an instance only needs storage for a __dict__, which is a dictionary containing the attributes. This works without problem for whatever multiple inheritance diagram.

These two cases have been combined (in Python 2.2) into the following "best-effort" appraoch: inheritence is only possible if there is at most one built-in base type. In this case, the memory layout can start with the layout expected for this built-in type, and contain the __dict__ afterwards to store any attribute required by the other base classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top