【Python】Object (Including Classes, Functions) Naming Conventions

Translation Notice
This article was machine-translated using DeepSeek-R1.

  • Original Version: Authored in Chinese by myself
  • Accuracy Advisory: Potential discrepancies may exist between translations
  • Precedence: The Chinese text shall prevail in case of ambiguity
  • Feedback: Technical suggestions regarding translation quality are welcomed

Core rules for naming:
Allowed characters: A-Z a-z
Underscore: _
Digits: 0-9 (Note: digits cannot be at the beginning)
==Chinese variable names are theoretically allowed but strongly discouraged.==

Valid name examples

1
2
3
abcdef	GoodCoder	AD_fhrygfuigfr
A_a_007	__NAME123	_P_T_
_123456	Cc_Dd	_

Invalid name examples

1
2
3
666Code	C++	1+1=2	(5)4
654ty54F	0.123	123456@qq.com
ccf-csp		atcoder&codeforces

Naming styles

First letter is usually lowercase (except for classes).
Since spaces are not allowed in object names, there are two common styles:

1
2
helloWorldStr = 'Hello World'
hello_world_str = 'Hello World'
  1. helloWorldStr style: Capitalize the first letter of each word except the first
  2. hello_world_str style: Separate words with underscores

Special case: Classes

Example:

1
2
3
class AppleTree:
    def dropApple():
        print('Apple dropped to the ground.')

AppleTree style: Capitalize the first letter of every word (including the first).

Built with Hugo
Theme Stack designed by Jimmy