Поскольку класс Manager владеет экземплярами, вопрос в том, как правильно укажите тип ситуации, поскольку управляемый класс экземпляра может иметь определяемый пользователем конструктор.
Пример:
Код: Выделить всё
class Base:
"""Base class for all instances"""
def __init__(self, base_arg1: int, base_arg2: float):
pass
InstanceType = TypeVar('InstanceType', bounds=Base) # must be subclass of Base
class Manager(Generic[InstanceType]):
"""The manager class. Is a factory of Instances, creates and owns them. However instances
may have custom extra arguments in their constructor. How to type-hint them correctly?"""
def __init__(self, instance_class: Type[InstanceType]):
self.factory = instance_class
pass
def new_instance(self, ??? ) # how to type hint the extra args of the constructor of InstanceType (without the base_args from Base.__init__)?
self.factory( ???, base_arg1=123, base_arg2=4.56 )
pass
class Instance(Base):
def __init__(self, extra_arg: bool, base_arg1: int, base_arg2: float): # note this has extra_arg: bool
pass
instance_manager = Manager(Instance) # note this will be correctly inferred as Manager[Instance]
instance_manager.new_instance(extra_arg=True) # How can this be correctly type-checked ??
Код: Выделить всё
class Manager(Generic[InstanceType]):
def __init__(self, instance_class: Callable[ [???], InstanceType]): # use Callable instead of Type
pass
- как захватить аргументы Callable и использовать их в определении ' new_instance' (но без (!) base_args)
- как обеспечить, чтобы аргументы содержали аргументы базового класса (т. е. base_arg1 и base_arg2).
Подробнее здесь: https://stackoverflow.com/questions/772 ... ces-are-fr