Код: Выделить всё
from abc import ABC, abstractmethod
from typing import Generic, TypeVar
class MyInterface(ABC):
@staticmethod
@abstractmethod
def default() -> int: ...
class SubclassA(MyInterface):
@staticmethod
def default() -> int:
return 0
class SubclassB(MyInterface):
@staticmethod
def default() -> int:
return 1
SomeSubclass = TypeVar('SomeSubclass', bound=MyInterface)
class InterfaceContainer(Generic[SomeSubclass]):
def check_if_default(self, value: int) -> bool:
return value == SomeSubclass.default() # AttributeError: 'TypeVar' object has no attribute 'default'
# optional, shows runtime error even without static type checking:
container = InterfaceContainer[SubclassA]()
container.check_if_default(42)
< /code>
Как я могу получить доступ к атрибутам типа, указанного как аргумент? это связанный вопрос, в котором я узнал, как получить доступ к аргументу, учитывая тип интерфейкконтейнер [subclassa] Интересно, если экземпляры общего класса полностью теряют информацию о своем типе, может быть, потому что она предназначена только для проверки типа?
Подробнее здесь: https://stackoverflow.com/questions/793 ... th-typevar
Мобильная версия