Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การทำงานของ Underscore (_) ใน Python

Underscore (_) มีความหมายพิเศษใน Python 5 กรณีหลัก:

1. เก็บค่า expression ล่าสุดใน interpreter

>>> 12 + 10
22
>>> _
22

2. เพื่อ ignore ค่าที่ไม่ต้องการ

>>> _, _, a = (1, 2, 3)
>>> a
3

3. ให้ความหมายพิเศษต่อชื่อตัวแปร/ฟังก์ชัน
Single leading underscore (_var) ใช้สำหรับ private variables/functions/classes ถูกละเว้นใน from module import *

4. แยกหลักของตัวเลข (Python 3.6+)

>>> a = 7_200_000_000  # 7.2 billion อ่านง่าย
>>> a
7200000000