简体   繁体   English

python中“ is”和“ isinstance”之间的区别

[英]Difference between “is” and “isinstance” in python

For the following code, str is variable of unicode type but 对于以下代码, str是unicode类型的变量,但是

str is unicode            # returns false
isinstance(str, unicode)  # returns true

Why is is return false? 为什么is是返回false?

is operator is used to check if both the objects are one and the same, whereas isinstance is used to check if the second parameter appears anywhere in the inheritance chain of the first parameter. is运算符用于检查两个对象是否都相同,而isinstance用于检查第二个参数是否出现在第一个参数的继承链中的任何位置。

So, when you do something like this 所以,当你做这样的事情

print(u"s" is unicode)

you are actually checking if u"s" is the unicode , but when you do 您实际上正在检查u"s"是否为unicode ,但是当您这样做时

print(isinstance(u"s", unicode))

you are checking if u"s" is of type unicode and the latter is actually True . 您正在检查u"s"是否为unicode类型,而后者实际上是True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM