我有一個方法,它有時返回一個非類型的值。那么我怎樣才能質疑一個非類型的變量呢?例如,我需要使用if方法
if not new:
new = '#'
我知道這是錯誤的方式,我希望你理解我的意思。
我想這是在這里回答的,顯然是在以前的某個地方。
如果您的方法返回的值只有bool(returnValue)等于False,那么if not new:應該可以正常工作。這有時發生在內置libs中——例如,re.match返回none或truthy match對象。
也可以在這里看到我關于python中的null和None的答案。
So how can I question a variable that is a NoneType?
使用is運算符,如下所示
if variable is None:
為什么會這樣?
由于None是python中NoneType唯一的單例對象,所以我們可以使用is操作符來檢查變量中是否有None。
引用is號文件,
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 is not y yields the inverse truth value.
由于只有一個None實例,因此is是檢查None的首選方法。
從馬嘴里聽到
引用了python的編碼風格指南-pep-008(由guido自己共同定義)。
Comparisons to singletons like None should always be done with is or is not, never the equality operators.
if variable is None:
...
if variable is not None:
...
根據亞歷克斯·霍爾的回答,也可以用isinstance來完成:
>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True
isinstance也是直觀的,但其復雜之處在于,它需要一條線。
NoneType = type(None)
這對于像int和float這樣的類型是不需要的。
由于你不能將NoneType分為子類,由于None是單體,因此不應使用isinstance來檢測None,而應按照公認的答案進行,并使用is None或is not None。
不在python3.6.7上工作
正如亞倫希爾的命令所指出的:
Since you can't subclass NoneType and since None is a singleton, isinstance should not be used to detect None - instead you should do as the accepted answer says, and use is None or is not None.
原始答案:
然而,最簡單的方法是,除了豆蔻的答案之外,如果沒有額外的行,可能是:isinstance(x, type(None))
So how can I question a variable that is a NoneType? I need to use if method
使用isinstance()不需要if語句中的is:
if isinstance(x, type(None)):
#do stuff
附加信息您還可以在一個isinstance()語句中檢查多個類型,如文檔中所述。只需將類型編寫為元組即可。
isinstance(x, (type(None), bytes))
由于你不能將NoneType分為子類,由于None是單體,因此不應使用isinstance來檢測None,而應按照公認的答案進行,并使用is None或is not None。
這個答案對python 3.6.7很有用。
Python 2.7:
x = None
isinstance(x, type(None))
或
isinstance(None, type(None))
=真
由于你不能將NoneType分為子類,由于None是單體,因此不應使用isinstance來檢測None,而應按照公認的答案進行,并使用is None或is not None。
哦,好吧!謝謝!
希望這個例子對您有所幫助)
print(type(None) # NoneType
所以,您可以檢查變量名的類型
#Example
name = 12 # name = None
if type(name) != type(None):
print(name)
else:
print("Can't find name")
不確定這是否回答了問題。但我知道我花了一段時間才弄明白。我在瀏覽一個網站,突然作者的名字不在了。所以需要一個支票聲明。
if type(author) == type(None):
my if body
else:
my else body
在這種情況下,author可以是任何變量,None可以是您要檢查的任何類型。
由于None是單體的,所以不應使用type來檢測None—而是應按照公認的答案進行,并使用is None或is not None。