概要
PythonのNoneは「値が存在しない」ことを明示する特殊なオブジェクトです。
他のプログラミング言語のnull/nilに相当し、変数の初期化や関数の戻り値として
広く利用されます。
特徴
- Noneのデータ型はNonType型です。
python
a = None print(a) >>> None print(type(a)) >>> <class 'NoneType'>
- NoneはFalse(偽)として判定されます。
python
if None: print("True") else: print("False") >>> False
使用用途
-
変数の初期化
未設定状態を明確に表示する。pythonuser_data = None # 後でデータが代入される
-
関数の戻り値
処理結果がない場合の戻り値として設定するpythondef fetch_data(data): # データ取得処理 return data if data > 10 else None print(fetch_data(0)) >>> None
-
関数のデフォルト引数
引数がない場合の判定が容易になるpythondef feb(num,L=None): if L is None: L = [] L.append(num) return L
気をつけること
-
比較演算子はisを使う
==だと結果が誤ることがある。pythonclass Example: def __eq__(self, other): # すべての比較をTrueとする return True x = Example() if x == None: print("xはNoneです") else: print("xはNoneではありません") >>> xはNoneです y = Example() if y is None: print("yはNoneです") else: print("yはNoneではありません") >>> yはNoneではありません
-
関数のデフォルト引数
pythondef feb(n,L=[]): L.append(n) return L print(feb(1)) print(feb(2)) print(feb(3)) >>> [1] [1,2] [1,2,3] def feb_2(n,L=None): if L is None: L = [] L.append(n) return L print(feb_2(1)) print(feb_2(2)) print(feb_2(3)) >>> [1] [2] [3]