是否可以仅在返回类型上约束(抽象)基方法,但保持参数的灵活性



是否可以仅在返回类型上约束(抽象(基方法,但保持该方法的参数完全灵活,以便子级以任何方式实现?

例如

import abc
class Mother(abc.ABC):
@abc.abstractmethod
def foo(self) -> int:
pass

class Child(Mother):
def foo(self, val: int) -> int:
return val * 2

这引发了:

$ mypy inheritance.py 
inheritance.py:12: error: Signature of "foo" incompatible with supertype "Mother"

因为Child使用未在Motherfoo方法中定义的参数val来实现foo

我认为唯一的方法是使Motherfoo可以接受的容器类型上通用,但我真正想要的是在Child中尽可能灵活,这样我就可以使用任何数量的参数,并且实际上是方法返回类型中的唯一约束。

这是我能想到的最好的:

import abc
class Mother(abc.ABC):
@abc.abstractmethod
def foo(self, *args, **kwargs) -> int:
pass

class Child(Mother):
def foo(self, *args, **kwargs) -> int:
return args[0] * 2

您可能需要在Child.foo中进行一些额外的检查。

相关内容

最新更新