A.4 Python关键字和内置函数
Python包含一系列关键字和内置函数,给变量命名时,知道这些关键字和内置函数很重要。编程中面临的一个挑战是给变量指定合适的名称,变量名可以是任何东西,只要它长短合适并描述了变量的作用。同时,不能将Python关键字用作变量名;也不应将Python内置函数的名称用作变量名,否则将覆盖相应的内置函数。
本节将列出Python关键字和内置函数的名称,让你知道应避免使用哪些变量名。
A.4.1 Python关键字
下面的关键字都有特殊含义,如果你将它们用作变量名,将引发错误:
False | class | finally | is | return |
None | continue | for | lambda | try |
True | def | from | nonlocal | while |
and | del | global | not | with |
as | elif | if | or | yield |
assert | else | import | pass | |
break | except | in | raise |
A.4.2 Python内置函数
将内置函数名用作变量名时,不会导致错误,但将覆盖这些函数的行为:
abs() | divmod() | input() | open() | staticmethod() |
all() | enumerate() | int() | ord() | str() |
any() | eval() | isinstance() | pow() | sum() |
basestring() | execfile() | issubclass() | print() | super() |
bin() | file() | iter() | property() | tuple() |
bool() | filter() | len() | range() | type() |
bytearray() | float() | list() | rawinput() | unichr() |
callable() | format() | locals() | reduce() | unicode() |
chr() | frozenset() | long() | reload() | vars() |
classmethod() | getattr() | map() | repr() | xrange() |
cmp() | globals() | max() | reversed()zip() | Zip() |
compile() | hasattr() | memoryview() | round() | _import() |
complex() | hash() | min() | set() | apply() |
delattr() | help() | next() | setattr() | buffer() |
dict() | hex() | object() | slice() | coerce() |
dir() | id() | oct() | sorted() | intern() |
注意 在Python 2.7中,print
是关键字而不是函数。另外,Python 3没有内置函数unicode()
。这两个单词都不应用作变量名。