[英]Trying to understand int type
我是Python的新手,正在尝试了解类型。 具体来说,有人可以解释为什么我得到这些结果吗?
>>> start = 1
>>> start is int
False
>>> type(start)
<class 'int'>
我问,因为我试图在脚本中运行测试,并且无法理解为什么测试失败,并且我害怕将输入转换为int,因为如果不是这样,我想确保它没有通过这项测试。 这是代码:
def slice(self, start=0, stop=0, step=1):
if start != 0 and start is not int:
for item in self.data:
if start in item:
start = self.data.index(item)
但是当我这样做时:
slice(1,10)
它无法通过“ start not not int”启动并进入for循环。
有什么帮助吗?
您应该这样做: isinstance(start, int)
。
start is int
检查是否start
是类型int
,不是否start
是该类型的一个实例int
。
>>> start = 1
>>> start is int
False
>>> isinstance(start, int)
True
从Python 3文档中:
运算符是否测试对象标识:并且仅当x和y是同一对象时,x is y才是true。 x不是y会产生反真值。 [4]
start是1,而int是Python类。 以下示例代码可能会为您提供帮助:
>>> start = 1
>>> start is int
False
>>> start == int
False
>>> start is 1
True
>>> start == 1
True
>>> type(start) == int
True
您应该使用type()或isinstance()(如Simeon建议)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.