Idiomatic multiple inheritance with python Abstract base classes

In simple terms, what I want is a tuple with one or two additional methods. __new__ or __init__ will not be changed.

I would like to create an abstract base class that is a subclass of collections.abc.Sequence . Then I want to use it for the main tuple subclass. The class diagram looks something like this:

  collections.abc.Sequence / \ / \ / \ MyABC tuple \ / \ / \ / MyClass 

Causes:

  • MyABC defines some user interfaces. It is there that third parties are not forced to subclass MyClass .
  • tuple needed for its performance and methods already implemented.

Questions:

  • Is it an idiomatic way to just write class MyClass(MyABC, tuple) or should I play with registers?
  • Are there any other obvious issues that I'm missing?
  • Will tuple lose space and performance due to subclass?
+4
source share
1 answer
  • Is it an idiomatic way to just write the MyClass class (MyABC, tuple) or do I need to play with registers?

    I think this is a rather idiomatic way to do this. This is also called " diamond inheritance . The __init__ method for MyClass may look like this .

  • Are there any other obvious issues that I'm missing?

    Well, it depends on some aspects that are not completely defined in the question, for example, what do you want to do for sure? How do you do this? How to use this new subclass pattern? How are the general / specific new methods that you have in your new class? Is there a more efficient / clean / readable / easy / any way to do this without subclassing? And even if so, is it worth it if you get more flexibility / readability and so on?

    As a rule, I would say that this is not only normal, but it is also advisable to create subclasses if you use it often enough and / or it will allow you to solve some problems more easily without radical / extremely undesirable side effects.

  • Will there be a loss of space and tuple performance due to a subclass?

    This is a difficult question. Again, depending on what you do and how you develop your subclass, etc., Maybe. Remember, for example, that tuples are an immutable type, and this property has some performance advantages over mutable types. So, if you, for example, somehow change this property, this could be a loss comparable to the original tuple. I'm also not quite sure how Python will see a subclass of the tuple. By that, I mean, I don’t know if Python will “blindly believe” that your class is immutable and still behaves exactly like a tuple. And if not, how bad it will be in your particular case. The immutable / mutable problem is just an example, other even more relevant problems may exist, but I could not say for sure ... Perhaps you could do a little test to measure performance.

Given some of these aspects (Guido himself) may also be a good idea.

Hope this helps!

+2
source

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


All Articles