如何解决在抽象方法中使用子类类型的抽象基类
我想使用抽象方法创建一个抽象基类,该方法返回实现该接口的任何子类的实例。除了我在下面创建的方法之外,还有没有更 Pythonic 的方法可以为 mypy 实现这一点?
在我的代码示例中,我将 Animal
类设为泛型。子类可以从 Animal 继承并将泛型参数指定为它自己,但对我来说它看起来笨重和错误。我想我可能遗漏了一些明显的东西。
请注意,在下面的代码中,当我对 Animal
进行子类化时,类定义使用了类似 Dog(Animal["Dog"])
的内容。它看起来不正确,但它适用于类型检查。有没有办法为抽象方法指明它必须返回与 self
相同的类型?
import abc
from typing import Generic,TypeVar
from __future__ import annotations
T = TypeVar('T')
class Animal(abc.ABC,Generic[T]):
@abc.abstractmethod
def procreate(self: T,other: T) -> T:
pass
class Dog(Animal["Dog"]):
def procreate(self,other: "Dog"):
return Dog()
class Cat(Animal["Cat"]):
def procreate(self,other: "Cat"):
return Cat()
dog = Dog()
dog.procreate(Cat())
解决方法
AFAIK 你不需要你的 Animal
类是 Generic
除非它是某种容器,例如Sequence
,我们可以将 TypeVar
用于特定方法
所以这应该按预期工作
import abc
from typing import TypeVar
from __future__ import annotations
T = TypeVar('T')
class Animal(abc.ABC):
@abc.abstractmethod
def procreate(self: T,other: T) -> T:
pass
class Dog(Animal):
def procreate(self,other: "Dog") -> "Dog":
return Dog()
class Cat(Animal):
def procreate(self,other: "Cat") -> "Cat":
return Cat()
dog = Dog()
dog.procreate(Cat())
mypy
将在最后一行通知错误:
> mypy test.py
test.py:26: error: Argument 1 to "procreate" of "Dog" has incompatible type "Cat"; expected "Dog"
Found 1 error in 1 file (checked 1 source file)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。