추상 부모 대신 자식 클래스 메서드가 자신을 반환하는 것으로 알려져 있도록 추상 부모 클래스 메서드를 입력하는 방법이 있습니까?
class Parent(ABC):
@abstractmethod
def method(self) -> [what to hint here]:
pass
class Child1(Parent)
def method(self):
pass
def other_method(self):
pass
class GrandChild1(Child1)
def other_method_2(self):
pass
이것은 PyCharm 또는 VScode의 python 플러그인과 같은 IDE의 자동 완성을 개선하기위한 것입니다.
따라서 일반적인 접근 방식은 여기 문서에 설명되어 있습니다.
import typing
from abc import ABC, abstractmethod
T = typing.TypeVar('T', bound='Parent') # use string
class Parent(ABC):
@abstractmethod
def method(self: T) -> T:
...
class Child1(Parent):
def method(self: T) -> T:
return self
def other_method(self):
pass
class GrandChild1(Child1):
def other_method_2(self):
pass
reveal_type(Child1().method())
reveal_type(GrandChild1().method())
그리고 mypy
우리에게 :
test_typing.py:22: note: Revealed type is 'test_typing.Child1*'
test_typing.py:23: note: Revealed type is 'test_typing.GrandChild1*'
이 작업을 수행하려면 type-variables를 계속 사용해야했기 때문에 원래 자식 클래스 주석에서 실제 자식 클래스를 사용하려고했을 때 (잘못된?) 손자 유형을 상속했습니다.
class Child1(Parent):
def method(self) -> Child1:
return self
나는 mypy와 함께 얻을 것입니다.
test_typing.py:22: note: Revealed type is 'test_typing.Child1'
test_typing.py:23: note: Revealed type is 'test_typing.Child1'
다시 말하지만 이것이 예상 / 올바른 동작인지 확실하지 않습니다. mypy 문서는 현재 경고가 있습니다 :
이 기능은 실험적입니다. 자체 인수에 대한 유형 주석으로 코드를 확인하는 것은 아직 완전히 구현되지 않았습니다. Mypy는 유효한 코드를 허용하지 않거나 안전하지 않은 코드를 허용 할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다