Python中抽象方法的静态类型检查 [英] Static type check for abstract method in Python
问题描述
如何确保实现抽象方法的方法遵守 python 静态类型检查.如果实现的方法的返回类型不正确,pycharm 有没有办法得到错误?
How do I make sure that a method implementing an abstract method adheres to the python static type checks. Is there a way in pycharm to get an error if the return type is incorrect for the implemented method?
class Dog:
@abc.abstractmethod
def bark(self) -> str:
raise NotImplementedError("A dog must bark")
class Chihuahua(Dog):
def bark(self):
return 123
所以对于上面的代码,我想得到某种提示,我的吉娃娃有问题
So for the above code I would want to get some sort of a hint that there is something wrong with my chihuahua
推荐答案
不,没有(简单的)方法可以强制执行此操作.
No there's not a (simple) way to enforce this.
实际上,您的 Chihuahua
没有任何问题,因为 Python 的鸭子类型允许您覆盖 bark
的签名(参数和类型).所以 Chihuahua.bark
返回一个 int
是完全有效的代码(虽然不一定是好的做法,因为它违反了 LSP).使用 abc
模块根本不会改变这一点,因为 它不强制方法签名.
And actually there isn't anything wrong with your Chihuahua
as Python's duck typing allows you to override the signature (both arguments and types) of bark
. So Chihuahua.bark
returning an int
is completely valid code (although not necessarily good practice as it violates the LSP). Using the abc
module doesn't change this at all as it doesn't enforce method signatures.
要强制"类型,只需将类型提示传递给新方法,这使其明确.它还导致 PyCharm 显示警告.
To "enforce" the type simply carry across the type hint to the new method, which makes it explicit. It also results in PyCharm showing a warning.
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
这篇关于Python中抽象方法的静态类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!