将student_name
是常量或没有?
student_name = ""
while len(student_name) > 1:
int(input(User input name of student and store this in variable student_name))
这取决于你将调用一个常数。 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
的现有属性。这里有一个惊喜;你可以在以后添加新的属性,而这些是可以改变的。
不,那里没有。你不能声明一个变量或价值在Python不变。只要不改变它。
如果你是在一个类中,相当于将是:
class Foo(object):
CONST_NAME = "Name"
如果不是,它只是
CONST_NAME = "Name"
下面的代码片段可以帮助你Link。