「_」は戻り値などの値を無視する際に使用します。
# 1, 2, 3を返す関数 def one_two_three(): return 1, 2, 3 # 3つ目の戻り値は不要 x, y, _ = one_two_three() print(x, y)
[paso ~] python3 test.py
1, 2
Pythonにはprivateやprotectedなど概念がありません。ただし、慣習として
となっています。 Python3.5系では先頭に「_」が2つだけ付いている(__XXXXのような)メンバーはPrivateとして認識してくれます。 よって、外部から参照した場合は例外が発生します。 また、アンダースコアで始まる名前のオブジェクトはインポートされません。
class TestClass: def __begin_two_us(self): print("メソッド名:__begin_two_us") def __enclose_two_us__(self): print("メソッド名:__enclose_two_us__") tc = TestClass() # よろしくないが、呼び出せてしまう。 tc.__enclose_two_us__() # 例外が発生する。 tc.__begin_two_us()
[paso ~] python3 test.py
メソッド名:__enclose_two_us__
Traceback (most recent call last):
File "test.py", line 15, in <module>
tc.__begin_two_us()
AttributeError: 'TestClass' object has no attribute '__begin_two_us'
[]で囲むとシーケンスデータ型の1つリストとして扱われます。リストデータ型は値の変更が可能(mutable)です。
()で囲むとシーケンスデータ型の1つタプルとして扱われます。リストデータ型との違いは後から値を変更することができない点です(immutable)。
COPYRIGHT © 2008 Deepnet Inc. ALL RIGHTS RESERVED.