简体   繁体   English

试图了解int类型

[英]Trying to understand int type

I'm new to Python and am trying to understand types. 我是Python的新手,正在尝试了解类型。 Specifically, can someone explain why I am getting these results? 具体来说,有人可以解释为什么我得到这些结果吗?

>>> start = 1
>>> start is int
False
>>> type(start)
<class 'int'>

I ask, because I am trying to run a test in a script and can't understand why it is failing the test, and I am afraid to cast the input as an int because, if it isn't, I want to make sure it doesn't pass this test. 我问,因为我试图在脚本中运行测试,并且无法理解为什么测试失败,并且我害怕将输入转换为int,因为如果不是这样,我想确保它没有通过这项测试。 here's the code: 这是代码:

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)

But when I do this: 但是当我这样做时:

slice(1,10)

It fails the "start is not int" and drops into the for loop. 它无法通过“ start not not int”启动并进入for循环。

Any help, please? 有什么帮助吗?

You should do: isinstance(start, int) . 您应该这样做: isinstance(start, int)

start is int checks whether start is the type int , not whether start is an instance of the type int . start is int检查是否start是类型int ,不是否start是该类型的一个实例int

>>> start = 1
>>> start is int
False
>>> isinstance(start, int)
True

From the Python 3 documentation: 从Python 3文档中:

The operators is and is not test for object identity: x is y is true if and only if x and y are the same object. 运算符是否测试对象标识:并且仅当x和y是同一对象时,x is y才是true。 x is not y yields the inverse truth value. x不是y会产生反真值。 [4] [4]

start is 1 while int is a Python class. start是1,而int是Python类。 Here's some sample code that may help you: 以下示例代码可能会为您提供帮助:

>>> start = 1
>>> start is int
False
>>> start == int
False
>>> start is 1
True
>>> start == 1
True
>>> type(start) == int
True

You should use type() or isinstance() (as Simeon suggested). 您应该使用type()或isinstance()(如Simeon建议)。

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

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