Effective Use of Underscores in Python: Tips and Tricks
This article explains how the underscore character in Python can be leveraged for quick console result reuse, selective tuple unpacking, protected and private attribute naming, and numeric readability, providing practical code examples that illustrate each technique for more efficient and readable code.
In Python, the underscore "_" serves multiple practical purposes that can streamline coding and data handling.
When working in the interactive console, "_" automatically stores the result of the last expression, allowing quick reuse without re‑typing.
# 忽略不需要的返回值
def fetch_data():
return 1, 'Alice', 'Data'
_, name, _ = fetch_data()
print(name)Underscores can also be used to ignore unwanted values when unpacking tuples or function returns, focusing only on needed items.
class Car:
def __init__(self):
self._speed = 0 # 受保护的属性
self.__name = None # 私有属性
def _increase_speed(self):
# 不建议外部直接调用
self._speed += 10Following naming conventions, a single leading underscore marks protected attributes, while double leading underscores trigger name‑mangling for private attributes, helping define clear APIs.
For large numbers, inserting underscores as visual separators improves readability, especially in financial or scientific calculations.
Mastering these underscore techniques enhances code clarity, efficiency, and professionalism in Python projects.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.