这可以接受吗?
from abc import ABC, abstractmethod
from typing import Any
class A(ABC):
@abstractmethod
def test(self) -> Any:
...
class B(A):
def test(self) -> int:
return 1
class C(A):
def test(self) -> str:
return "yes"
澄清一下,我知道他们可以,我只是想知道这在良好实践方面是否可以接受。
答案 0 :(得分:0)
技术上是的,但最好定义一个泛型返回类型并让子类返回此返回类型的子类。
例如,您可以定义一个类 GenericType
并有两个子类 GenericTypeA
和 GenericTypeB
。然后你可以做这样的事情:
from abc import ABC, abstractmethod
class A(ABC):
@abstractmethod
def test(self) -> GenericType:
...
class B(A):
def test(self) -> GenericTypeA:
...
class C(A):
def test(self) -> GenericTypeB:
...
通过这种方式,A 类告诉用户测试方法总是返回一个 GenericType
对象,它本身就是一个抽象类。这样用户就知道类 A 的任何子类都将返回 GenericType
的子类。