如何确保实现抽象方法的方法符合python静态类型检查。如果所实现的方法的返回类型不正确,pycharm中有没有办法得到一个错误?
class Dog:
@abc.abstractmethod
def bark(self) -> str:
raise NotImplementedError("A dog must bark")
class Chihuahua(Dog):
def bark(self):
return 123因此,对于上面的代码,我希望得到一些提示,即我的吉娃娃有问题
发布于 2019-01-09 07:07:35
不,没有一种(简单的)方法来实施这一点。
实际上,您的Chihuahua没有任何问题,因为Python的鸭子类型允许您覆盖bark的签名(包括参数和类型)。因此,返回int的Chihuahua.bark是完全有效的代码(尽管不一定是好的做法,因为它违反了the LSP)。作为it doesn't enforce method signatures,使用abc模块根本不会改变这一点。
要“强制”该类型,只需将类型提示传递给新方法,从而使其显式。它还会导致PyCharm显示一个警告。
import abc
class Dog:
@abc.abstractmethod
def bark(self) -> str:
raise NotImplementedError("A dog must bark")
class Chihuahua(Dog):
def bark(self) -> str:
# PyCharm warns against the return type
return 123https://stackoverflow.com/questions/54087885
复制相似问题