Python学习精粹011:给变量命名与赋值

“好名字可能预示着好的开始。”

标识符是指以符号来标识事物以便识别。在编程语言中,标识符是有特定含义的字符,用来识别变量、常量、函数、类等。变量名即是标识符的一种。

在Python中,给变量命名时,必须遵守一些约定的规则,否则将引发错误,具体如下:

1. 变量名只能包含字母、数字和下划线(_),且必须以字母或下划线(_)开头,不能以数字开头。

如下所示:

numer1 = 123 #@01 

number_1 = 123 #@02 

1number = 123 #@03 

1_number = 123 #@04 

number$1 = 123 #@05 

在#@01、#@02处的变量命名是合法的。

在#@03、#@04、#@05处的变量命名,以数字开头或包含有特殊字符(如$),是不合法的。如强制使用非法变量,会提示语法错误信息“SyntaxError: invalid syntax”。

需要注意的是,使用中文字符来命名变量虽然合法,但不建议用英文字母、数字和下划线(_)之外的其他字符来命名变量。

如下所示:

变量1 = 'Hello'

print(变量1)

2. 变量名不能包含空格,但可以用下划线(_)来分隔。

如下所示:

one message = "After all, tomorrow is another day!" #@01 

one_message = "After all, tomorrow is another day!" #@02 

message_1 = "After all, tomorrow is another day!" #@03 

在#@01处,变量名包含了空格,是非法的变量名。

在#@02、#@03处,变量名中通过下划线(_)来分隔单词或数字等,是合法的变量名。

3. 不要使用Python关键字(又称:保留字)作为变量名,因为这些关键字在Python中有特殊意义。

如关键字def用于定义一个函数,关键字import用于导入一个指定模块等。

在当前最新版本的Python 3.12中,关键字有35个,通过执行以下Python代码可查看这些关键字:

>>> import keyword

print(keyword.kwlist)

打印输出Python的所有关键字:

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

如果要判断变量名(如“continue”)是否为Python关键字,可通过执行以下语句:

import keyword

print(keyword.iskeyword('continue'))

如返回True,则表示为Python关键字,否则不是。

4. 避免使用Python内置标识符作为变量名。如果变量名与内置标识符相同,则会引发错误或变量会覆盖相应的内置标识符的用途。

需要注意的是:Python关键字并不都是包含在内置标识符中,只有FALSE、None、TRUE关键字包含在内置标识符中;内置函数名则全都被包含在内置标识符中;Python关键字与内置函数名并无同名的。

如Python内置的print函数用于打印输出,在交互式解释器中执行以下Python代码:

>>> print = 'I am big!'

>>> print(print)

Traceback (most recent call last):

  File "<pyshell#1>", line 1, in <module>

    print(print)

TypeError: 'str' object is not callable

如上所示,将会引发错误“TypeError: 'str' object is not callable”,也就是说,当尝试调用一个不可调用的对象时,会发生该错误。

接下来,在交互式解释器中执行以下Python代码:

>>> print(abs) #@01 

<built-in function abs>

>>> print(abs(-123)) #@02 

123

>>> abs = 'You talking to me?' #@03 

>>> print(abs) #@04 

You talking to me?

在#@01处,执行结果表明abs为Python内置函数;

在#@02处,执行结果表明使用了abs函数来计算数字的绝对值;

在#@03处,给变量abs赋值时,即将同名的内置函数abs覆盖了,因而在#@04处的执行结果将为abs变量的值。

下面列出了Python 3.12中的内置函数:

表3.2 Python内置函数

A

E

L

R

abs()

enumerate()

len()

range()

aiter()

eval()

list()

repr()

all()

exec()

locals()

reversed()

anext()

round()

any()

F

M

ascii()

filter()

map()

S

float()

max()

set()

B

format()

memoryview()

setattr()

bin()

frozenset()

min()

slice()

bool()

sorted()

breakpoint()

G

N

staticmethod()

bytearray()

getattr()

next()

str()

bytes()

globals()

sum()

O

super()

C

H

object()

callable()

hasattr()

oct()

T

chr()

hash()

open()

tuple()

classmethod()

help()

ord()

type()

compile()

hex()

complex()

P

V

I

pow()

vars()

D

id()

print()

delattr()

input()

property()

Z

dict()

int()

zip()

dir()

isinstance()

divmod()

issubclass()

_

iter()

__import__()

更多信息可参见https://docs.python.org/3.12/library/functions.html

再执行以下代码:

>>> print(object) #@01 

<class 'object'>

>>> object = 'May the Force be with you.' #@02 

>>> print(object) #@03 

May the Force be with you.

在#@01处,执行结果表明为内置类object;

在#@02处,给变量object赋值时,即将同名的内置类object覆盖了,因而在#@03处的执行结果将为变量object的值。

而要获取Python 3.12中内置标识符的完整列表(共计158个),可以在交互式解释器中执行以下代码:

import builtins

print(dir(builtins))

其中,buildtins模块提供了对Python所有内置标识符的直接访问,使用builtins模块作为dir函数的参数,则会返回builtins模块的所有属性的列表。

上述代码的执行结果如下:

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

也可以在交互式解释器中,通过执行命令dir(__builtins__)来查看当前版本Python中的所有内置标识符。

除了遵守上述规则,还可参考这些良好实践:

5. 变量名可以为任意长度。为了更具可读性,变量名应简洁明了有意义。

如果只用缩写名称有可能使其含义模糊(如a、b、c),所以,首先应清晰地描述变量的具体用途,如可以使用完整的单词,多个单词组合可用下划线(_)分隔以增加可读性(如user_name、user_code),但不要冗长得影响阅读。

此外,建议不要使用拼音与英文混合的方式。

6. 在Python中,是区分大小写的。

如Msg、msg、MSG,是3个不同的变量名。

变量名只使用大写字母是合法的,但依照惯例,建议只使用小写字母为变量命名,因为在Python中,并无真正的常量,任何变量的值都可以修改,故而可用大写字母来将一个变量标记为常量,必要时用下划线(_)分隔单词以增加可读性。

此外,建议将标记为常量的变量集中放在程序模块的顶部。

7. 除了都用小写字母作为变量名,也可使用驼峰式命名法(CamelCase)。

即第一个单词小写,后续的每个单词的第一个字母都是大写,如numberOfCustomers、bookName。

8. 慎用大写字母O和小写字母l。

在有些字体中,大写字母O和小写字母l,会与数字0和1很难区分,有可能会被错认成数字0和1。

当然,可供选择的一个次优方法是,在操作系统中安装易于分辨这些字符的字体,如Adobe公司开源的Source Code Pro字体(下载地址为https://github.com/adobe-fonts/source-code-pro),并在文本编辑器或IDE中设置与使用该字体。

9. 不要在同一个程序模块的不同上下文中使用相同的变量名,也不要在一个方法内用同一个变量做不同的用途。

  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值