[英]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.