什么时候应该在Python中使用类型检查? [英] When should I use type checking (if ever) in Python?

查看:125
本文介绍了什么时候应该在Python中使用类型检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Python,作为一名主要的Java开发人员,我最大的问题是了解何时以及何时不使用类型检查.大多数人似乎在说Python代码不需要进行类型检查,但是在很多情况下,我认为这是必要的.例如,假设我需要使用一个方法参数来执行算术运算,为什么我不应该确保该参数是数字数据类型呢?

I'm starting to learn Python and as a primarily Java developer the biggest issue I am having is understanding when and when not to use type checking. Most people seem to be saying that Python code shouldn't need type checking, but there are many cases when I believe it is necessary. For example, let's say I need to use a method parameter to perform an arithmetic operation, why shouldn't I make sure the argument is a numeric data type?

此问题不仅限于功能.对于类变量,我也经历了同样的思考过程.为什么以及何时不应该使用属性(使用@property)而不是定期执行的类变量来检查类型?

This issue is not only limited to functions. The same thought process occurs to me for class variables. Why and when should I or shouldn't I use properties (using @property) to check type instead of regularly implemented class variables?

这对我来说是一种新的发展方式,希望能帮助我理解.

This is a new way of approaching development for me so I would appreciate help understanding.

推荐答案

不是 Pythonic 来检查类型信息,而是使用鸭子类型:如果它看起来像鸭子一样走路像鸭子一样, quacks 像鸭子一样,然后鸭子.

It's not Pythonic to check type info, use duck typing instead: if it looks like a duck, walks like a duck and quacks like a duck then it is a duck.

def quack(duck):
    duck.quack()

这仅在duck具有可调用的quack属性时运行,否则将引发异常,否则可能被调用者捕获.

this will only run if duck has a callable quack attrubute, it will raise an exception otherwise which can be caught by the caller.

这篇关于什么时候应该在Python中使用类型检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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