student_name 是否是常量?
student_name = ""
while len(student_name) > 1:
int(input(User input name of student and store this in variable student_name))
请您参考如下方法:
这取决于您所说的常量。 Python 具有不可变对象(immutable对象)。像字符串。请记住,在 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 之后,您不能更改 existing 属性。这里有一个惊喜;您可以稍后添加新属性,并且可以更改这些属性。
