【发布时间】:2015-10-24 08:58:02
【问题描述】:
Python 3.5 中的new features 之一是类型提示,灵感来自mypy。
打字:PEP 484 - 输入提示。
我想测试它,但它没有按预期工作。
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) 和本地测试了它。我错过了什么,让它发挥作用吗?这种类型在运行时不起作用吗?
【问题讨论】:
-
"运行时不进行类型检查。" 就在第一部分。
标签: python python-3.x type-hinting python-typing