Python 3.5 类型提示不会导致错误 [英] Python 3.5 type hinting does not result in an error

查看:36
本文介绍了Python 3.5 类型提示不会导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python 3.5 中的新功能之一是受这个项目.

One of the new features in python 3.5 is type hinting inspired from this project.

输入:PEP 484 – 输入提示.

typing: PEP 484 – Type Hints.

我想测试它,但它没有按预期工作.

I want to test it, but it does not work as expected.

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 app.py)?

I would expect an error because I am expecting a bool as return. I tested it on python:3.5 (docker) and local. Did i miss something, to make it work? Does this typing not work at runtime (like python app.py)?

推荐答案

请参阅您链接到的 PEP 中摘要的第五段:

See the fifth paragraph of the abstract in the PEP you link to:

虽然这些注释在运行时通过通常的 __annotations__ 属性可用,在运行时不进行类型检查.相反,该提案假设存在一个单独的离线类型检查器,用户可以自愿运行其源代码

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 类型提示不会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆