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

Valid Python Identifiers (กฎการตั้งชื่อ)

Identifier = ชื่อตัวแปร ฟังก์ชัน คลาส โมดูล แพ็กเกจ

กฎ Syntax

  • ขึ้นต้นด้วย: ตัวอักษร (a-z, A-Z) หรือ Underscore (_)
  • ตามด้วย: ตัวอักษร, ตัวเลข (0-9), Underscore ได้ไม่จำกัด
  • Case-sensitive: name ≠ Name ≠ NAME
  • ห้ามใช้ Keywords

Convention (PEP 8)

ประเภทStyleตัวอย่าง
ClassCapWords (PascalCase)MyClass
Function/Variable/Modulesnake_casemy_function
ConstantUPPER_SNAKE_CASEMAX_SIZE
Private (Internal)Leading Underscore_internal_var
Strong Private (Name Mangling)Double Leading Underscore__private
Special (Dunder)Double Leading & Trailing__init__, __str__

ตัวอย่าง Valid/Invalid

# Valid
my_var, _private, MyClass, CONSTANT, var2

# Invalid
2var, my-var, class, for, my.var