本文由我司收集整编,推荐下载,如有疑问,请与我司联系
关键字:
is
和
=
在
python
中有什么区别
关键字:
is
和
=
在
python
中有什么区别
[
英
]What
is
the
difference
between
keyword: is and == in python the python keyword is is supposed to be used in place of the
== operator according to python style guides.
根据
python
样式指南,
python
关键字应该用于代替
==
运算符。
However they don’t always do exactly the same thing as shown here. Why? What is the
actual difference, and what is the proper usage?
但是,它们并不总是与此处所示完全相同。为什么?实际的差异是什么,正确的
用法是什么?
import
unittestclass
testIS(unittest.TestCase):
def
test_is(self):
self.assertEqual(1,1)if
__name__ == ‘__main__’: unittest.main() Which works... but the following does not...
哪个有效
...
但以下不
...
import
unittestclass
testIS(unittest.TestCase):
def
test_is(self):
self.assertEqual(1,1)if
__name__ is ‘__main__’: unittest.main() 5
is will return True if two variables point to the same object, == if the objects referred to
by the variables are equal.
如果两个变量指向同一个对象,则返回
True;
如果变量引用的对象相等,则返回
=
。
a = [1, 2, 3] b = a b is a
b == a b = a[:] b is aFalse b == a 7
== tests for equality. Two non-identical objects can be equal.
==
测试平等。两个不相同的对象可以相等。
is tests for identity, i.e. whether both refer to the same one object.
是对身份的测试,即两者是否都指向同一个对象。
2
if
money_in_wallet
is
money_that_was_in_wallet(two_weeks_ago):
print(“I
still
live
with
my
parents
and
have
no
income
or
expenses”)elif
money_in_wallet
==