標識符
標識符是變量、函數、類、模塊和其他對象的名稱。
①在 Python 里,標識符由字母、數字、下划線組成。
在 Python 中,所有標識符可以包括英文、數字以及下划線(_),但不能以數字開頭。
②Python 中的標識符是區分大小寫的。
③以下划線開頭的標識符是有特殊意義的。
以雙下划線開頭的 __foo 代表類的私有成員,__foo(self)代表類的私有方法,不能直接從外部調用,需通過類里的其他方法調用。
以雙下划線開頭和結尾的 __foo__ 代表 Python 里特殊方法專用的標識,如 __init__() 代表類的構造函數。
④避免使用python預定義標識符名作為自定義標識符名。例如,NotImplemented、Ellipsis、int、float、list、str、tuple等
保留關鍵字
關鍵字即預定義保留標識符。
關鍵字不能在程序中用作標識符,否則會產生編譯錯誤。
False | class | from | or |
None | continue | global | pass |
True | def | if | raise |
and | del | import | return |
as | elif | in | try |
assert | else | is | while |
async | except | lambda | with |
await | finally | nonlocal | yield |
break | for | not |
python預定義標識符
Python 語言包含了許多預定義的內置類、異常、函數等,如 float、input、print、ArithmeticError等,應避免使用Python 預定義標識符名作為自定義標識符名。使用Python 內置函數 dir(__builtins__) 可以查看所有的內置異常名和函數名。
abs() | all() | any() | basestring() | bin() |
bool() | bytearray() | callable() | chr() | classmethod() |
cmp() | compile() | complex() | delattr() | dict() |
dir() | divmod() | enumerate() | eval() | execfile() |
file() | filter() | float() | format() | frozenset() |
getattr() | globals() | hasattr() | hash() | help() |
hex() | id() | input() | int() | isinstance() |
issubclass() | iter() | len() | list() | locals() |
long() | map() | max() | memoryview() | min() |
next() | object() | oct() | open() | ord() |
pow() | print() | property() | range() | raw_input() |
reduce() | reload() | repr() | reversed() | zip() |
round() | set() | setattr() | slice() | sorted() |
staticmethod() | str() | sum() | super() | tuple() |
type() | unichr() | unicode() | vars() | xrange() |
Zip() | __import__() | apply() | buffer() | coerce() |
intern | |
python命名規則
類型 | 命名規則 | 舉例 |
---|---|---|
模塊名/包名 | 全小寫字母,簡單有意義,如果需要可以使用下划線 | math、sys |
函數名 | 全小寫字母,可以使用下划線增加可閱讀性 | foo(), my_func() |
變量名 | 全小寫字母,可以使用下划線增加可閱讀性 | age、my_var |
類名 | 采用PascalCase命名規則,由多個單詞組成名稱,其每個單詞的首字母大寫 | MyClass |
常量名 | 全部大寫字母,可以使用下划線增加可閱讀性 | LEFT、TAX_RATE |