“是"是怎么来的?在 python 中工作? [英] How does "is" work in python?

查看:45
本文介绍了“是"是怎么来的?在 python 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请有人解释如何在if"条件下使用is".我正在使用分数模块,但遇到了一些问题:

<预><代码>>>>分数(0, 1) 是 0错误的>>>浮动(分数(0, 1))0.0>>>浮动(分数(0,1))是0.0错误的

我发现唯一有效的是:

<预><代码>>>>F = 分数(a,b)>>>如果 F > = 0:...如果 F(0, 1) <= 0:……

有没有办法在这里使用是"?谢谢.

解决方案

is 检查对象身份.如果两个名称引用同一个对象,则返回 true.一个典型的用例是检查名称是否引用 None:

如果 foo 是 None:# 做东西

Can please someone explain how one may use 'is' in an 'if' condition. I am working with the fractions module, and I'm having some trouble:

>>> Fraction(0, 1) is 0
False
>>> float(Fraction(0, 1))
0.0
>>> float(Fraction(0,1)) is 0.0
False

The only thing I found to work is:

>>> F = Fraction(a,b)
>>> if F >= 0:
...     if F(0, 1) <= 0:
...                      ...

Is there a way to use 'is' here? Thanks.

解决方案

is checks for object identity. It returns true if two names refer to the same object. One typical usecase is to check if a name refers to None:

if foo is None:
    # do stuff

这篇关于“是"是怎么来的?在 python 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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