あなたが参照している本は明らかにの意味を大幅に単純化しようとしていNone
ます。Python 変数には、初期の空の状態はありません。Python 変数は、定義されている場合にのみバインドされます。値を指定せずに Python 変数を作成することはできません。
>>> print(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> def test(x):
... print(x)
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: test() takes exactly 1 argument (0 given)
>>> def test():
... print(x)
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in test
NameError: global name 'x' is not defined
しかし、変数が定義されているかどうかに応じて、関数の意味を変えたい場合があります。次のデフォルト値を持つ引数を作成できますNone
。
>>> def test(x=None):
... if x is None:
... print('no x here')
... else:
... print(x)
...
>>> test()
no x here
>>> test('x!')
x!
この値が特別なNone
値であるという事実は、この場合にはそれほど重要ではありません。任意のデフォルト値を使用できました。
>>> def test(x=-1):
... if x == -1:
... print('no x here')
... else:
... print(x)
...
>>> test()
no x here
>>> test('x!')
x!
…しかし、None
周りにいることで 2 つの利点が得られます。
-1
意味が不明確なような特別な値を選択する必要はありません。
- 私たちの関数は、実際に
-1
は通常の入力として処理する必要があるかもしれません。
>>> test(-1)
no x here
おっとっと!
そのため、この本は主にリセットという言葉の使用において少し誤解を招くものです。名前への割り当てNone
は、その値が使用されていないか、関数が何らかのデフォルトの方法で動作する必要があるが、値をリセットdel
する必要があるというプログラマーへのシグナルです。元の未定義の状態にするには、次のキーワードを使用する必要があります。
>>> x = 3
>>> x
3
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined