静态类型检查Python中的抽象方法

Rya*_*yan 7 python pycharm

如何确保实现抽象方法的方法遵守python静态类型检查。如果返回类型对于所实现的方法不正确,pycharm中是否有办法获取错误?

class Dog:
    @abc.abstractmethod
    def bark(self) -> str:
        raise NotImplementedError("A dog must bark")

class Chihuahua(Dog):
    def bark(self):
        return 123
Run Code Online (Sandbox Code Playgroud)

所以对于上面的代码,我想得到某种暗示,我的吉娃娃狗出了毛病

101*_*101 6

不,没有一种(简单的)方法可以执行此操作。

实际上,您没有任何问题,Chihuahua因为Python的鸭式输入允许您覆盖的签名(参数和类型)bark。因此,Chihuahua.bark返回int完全有效的代码(尽管不一定是好的做法,因为它违反了LSP)。使用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 123
Run Code Online (Sandbox Code Playgroud)