这取决于您所说的常量。 Python 有不可变的对象。像字符串。请记住,在 Python 中,变量基本上是对象上的标签。所以如果你写
x = 'foo'
标签x 用于不可变字符串'foo'。如果你当时这样做
x = 'bar'
你没有改变字符串,你只是把标签挂在不同的字符串上。
但不可变的对象并不是我们通常认为的常量。在 Python 中,常量可以被认为是不可变的标签;一个变量(标签),一旦分配就不能更改。
直到最近,Python 才真正拥有这些。根据约定,全大写名称表示不应更改。但这不是由语言强制执行的。
但是从 Python 3.4(也向后移植到 2.7)开始,我们有了 enum 模块,它定义了不同类型的枚举类(实际上是单例)。枚举基本上可以用作常量组。
这是一个比较文件的函数返回枚举的示例;
from enum import IntEnum
from hashlib import sha256
import os
# File comparison result
class Cmp(IntEnum):
differ = 0 # source and destination are different
same = 1 # source and destination are identical
nodest = 2 # destination doesn't exist
nosrc = 3 # source doesn't exist
def compare(src, dest):
"""
Compare two files.
Arguments
src: Path of the source file.
dest: Path of the destination file.
Returns:
Cmp enum
"""
xsrc, xdest = os.path.exists(src), os.path.exists(dest)
if not xsrc:
return Cmp.nosrc
if not xdest:
return Cmp.nodest
with open(src, 'rb') as s:
csrc = sha256(s.read()).digest()
if xdest:
with open(dest, 'rb') as d:
cdest = sha256(d.read()).digest()
else:
cdest = b''
if csrc == cdest:
return Cmp.same
return Cmp.differ
这样您就不必在每次使用它时查看compare 的返回值的实际含义。
在定义enum 后,您无法更改它的现有 属性。这里有一个惊喜;您可以稍后添加新属性,并且可以更改这些属性。