Underscore _ - Nhiều ý nghĩa khác nhau
Các cách dùng _
Phần tiêu đề “Các cách dùng _”1. Last result trong REPL
Phần tiêu đề “1. Last result trong REPL”>>> 2 + 35>>> _5>>> _ * 2102. Throwaway variable
Phần tiêu đề “2. Throwaway variable”# Không quan tâm giá trịfor _ in range(5): print("Hello")
# Unpackingx, _, z = (1, 2, 3) # Bỏ qua giá trị thứ 23. Number separator
Phần tiêu đề “3. Number separator”# Dễ đọcmillion = 1_000_000billion = 1_000_000_000
# Binarybits = 0b_1010_11004. Private (convention)
Phần tiêu đề “4. Private (convention)”# Single underscoreclass MyClass: def _internal(self): # "Private" method pass
# Double underscoreclass MyClass: def __private(self): # Name mangling pass5. Magic methods
Phần tiêu đề “5. Magic methods”class MyClass: def __init__(self): # Constructor pass
def __str__(self): # String representation pass6. Internationalization (i18n)
Phần tiêu đề “6. Internationalization (i18n)”# Common conventionfrom gettext import gettext as _
print(_("Hello, World!"))Tóm tắt
Phần tiêu đề “Tóm tắt”Underscore
_:
- REPL: Last result
- Loop: Throwaway variable
- Number: Separator (1_000_000)
_name: Protected (convention)__name: Private (name mangling)__name__: Magic methods
Patterns:
for _ in range(n): ... # Throwawayx, _, z = values # Ignore middlenum = 1_000_000 # Readability