Subclass `type` and` tuple`

For a fun (and valid, but not connected) reason, I want to do the following:

class Head(type, tuple): pass 

But this leads to

 TypeError: multiple bases have instance lay-out conflict 

(on python3.3 and python2.7)

How to get around this?

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

+4
source share
1 answer

I cannot find a suitable reference to it, but the fact is that Python does not support multiple inheritance of several built-in types. You cannot create a class that inherits both "type" and "tuple", or "int" and "str", or most other combinations. Basically, the internal reason is related to the internal layout of instances: the memory layout of the int object contains storage for an integer value; but this is incompatible with the layout of the str object, which contains memory for characters. It is not possible to create an instance of a class that will inherit from both, because we do not know what memory format it should have.

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

These two cases were combined (in Python 2.2) into the following โ€œbest effortโ€: inheritance is only possible if there is no more than one built-in base type. In this case, the memory layout may begin with the layout expected for this built-in type, and contain __dict__ subsequently to store any attributes needed for other base classes.

+2
source

Source: https://habr.com/ru/post/1484057/