Made an adapter. The adapter accepts a class and returns itself.

class Adapter(metaclass=ABCMeta): def __init__(self, adaptable_object): self._adaptable_object = adaptable_object @property def adaptable_object(self) -> Adapter: # Этот метод приходится перегружать return self.adaptable_object class B(Adapter): @property def adaptable_object(self) -> "B": # Типа перегрузил. return super().adaptable_object 

Is it possible to specify the caller itself as the type of the returned object?

Or maybe some other solution is to not overload the method in each new heir?

  • If adaptable_object() is a type of constructor that must return an instance subclass, and not just a base class variable, then you can try a generic self : TypeVar('T', bound='Adatpter') instead of Adapter. In general, be suspicious of cases where you use inheritance, but cannot use a particular variable as an instance of the base class — if you are trying to pull a particular subclass from the base method, you should consider delegation in this case - jfs
  • I don’t know how you guessed it, but in the original version I really implemented a parallel constructor, but here I didn’t write a little, but apparently the level of telepathy is very high :-) - Mr Fix
  • In short, I adapted via @classmethod , and created through __init__ , I initially thought that this would be more close to the python, but there was a lot of inconvenience. As a result, I began to adapt through __init__ , and create new instances through @classmethod , and problems of this kind fell off, and the code became smaller. - Mr Fix
  • Yes, using @ class methods for alternative constructors is idiomatic, for example: datetime.now, datetime.fromtimestamp are classmethod (inheritance returns instances of subclasses, and not base class by such methods) - jfs

1 answer 1

The description of the type of the returned object does not affect anything; it is used only for static code analysis by third-party tools or for prompts in the IDE.

  • The stump is clear. For this and need. - Mr. Fix