new features 之一在 Python 3.5 中是类型提示,灵感来自 mypy .
typing: PEP 484 – Type Hints.
我想测试它,但它没有按预期工作。
import typing
class BankAccount:
def __init__(self, initial_balance: int = 0) -> None:
self.balance = initial_balance
def deposit(self, amount: int) -> None:
self.balance += amount
def withdraw(self, amount: int) -> None:
self.balance -= amount
def overdrawn(self) -> bool:
return str(self.balance < 0)
my_account = BankAccount(15)
my_account.withdraw(5)
print(type(my_account.overdrawn()))
结果:
<class 'str'>
我预料到会出现错误,因为我期望 bool
作为返回类型。我在 Python 3.5 (docker) 和本地测试了它。我错过了什么,让它发挥作用吗?这种键入在运行时不起作用吗?
最佳答案
请参阅您链接到的 PEP 中摘要的第五段:
While these annotations are available at runtime through the usual
__annotations__
attribute, no type checking happens at runtime . Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily
关于Python 3.5 类型提示不会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33316345/