是否可以仅在 return 类型上约束(抽象)基方法但保持参数灵活?
Is it possible to constrain an (abstract) base method only on the return type but keep the parameters flexible?
是否可以仅在 return 类型上限制(抽象)基方法,但保持该方法的参数完全灵活,以便儿童以他们想要的任何方式实施?
例如
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
实现 foo
的参数 val
未在 Mother
的 foo
方法中定义。
我看到的唯一方法是使 Mother
通用于 foo
会接受的某些容器类型,但我真正想要的是在 Child
中尽可能灵活这样我就可以使用任意数量的参数,并且实际上只在方法的 return 类型中受到约束。
这是我能想到的最好的:
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
。
是否可以仅在 return 类型上限制(抽象)基方法,但保持该方法的参数完全灵活,以便儿童以他们想要的任何方式实施?
例如
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
实现 foo
的参数 val
未在 Mother
的 foo
方法中定义。
我看到的唯一方法是使 Mother
通用于 foo
会接受的某些容器类型,但我真正想要的是在 Child
中尽可能灵活这样我就可以使用任意数量的参数,并且实际上只在方法的 return 类型中受到约束。
这是我能想到的最好的:
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
。