1. 程式人生 > >關於Python中的None和null

關於Python中的None和null

在很多程式語言中,都有null這個值,作為值賦予給變數。

Python中也有,但是是用None。使用None的原因是:
1)null這個單詞不夠友好,對初學者來說不好理解。
2)面向物件的語言都傾向用駝峰命名法,None符合駝峰命名法。

在Python中,None是一個物件:
 

>>> print(type(None))
<class 'NoneType'>

什麼時候可以用Python的None:
1)用於判斷一個函式或者方法是否生效,例如:
 

# pseudocode
import MyDatabase

database_connection = None

# try to connect database
try:
    database_connection = MyDatabase(host, port, user_name, user_password)
except Exception as e:
    pass

if database_connection is None:
    print("fail to connect database")
else:
    print("database connected")

2)檢查一個變數是否為None
這點上要特別注意的是:Python中,一般我們用於判斷一個變數是否為None有兩種方式,一種是is,一種是==。平時可能這兩種方式都可以得到正確的結果,但是不建議用== 方式。因為 == 是一個類中的內建函式__eq__,而定義類的時候,是允許重寫內建函式的,所以可能因為重寫了__eq__,導致使用 == 方式來判斷出現錯誤。例如:
 

# pseudocode
class MyClass:
    def __eq__(self, my_object):
    # No matter what, we return True, which will cause some errors
        return True

my_class = MyClass()

if my_class is None:
    print("my_class is None, using the is keyword")
else:
    print("my_class is not None, using the is keyword")

if my_class == None:
    print("my_class is None, using the == syntax")
else:
    print("my_class is not None, using the == syntax")

以上的虛擬碼,因為重寫了__eq__方法,讓它不管在任何時候,都返回True,所以my_class本來不是None的,卻被認為是None。