【问题标题】:How do you know what a constant is?你怎么知道常数是什么?
【发布时间】:2016-05-05 04:52:25
【问题描述】:

student_name 是否为常数?

student_name = ""

while len(student_name) > 1:
    int(input(User input name of student and store this in variable student_name))

【问题讨论】:

  • 不,它不会是一个常数,因为值可能正在改变......虽然有点不清楚,因为你显示的代码实际上并没有改变值,它只是 暗示 值应该在 while 循环中改变。

标签: python constants


【解决方案1】:

这取决于您所说的常量。 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 后,您无法更改它的现有 属性。这里有一个惊喜;您可以稍后添加新属性,并且可以更改这些属性。

【讨论】:

    【解决方案2】:

    不,没有。您不能在 Python 中将变量或值声明为常量。只是不要改变它。

    如果您在课堂上,则相当于:

    class Foo(object):
        CONST_NAME = "Name"
    

    如果没有,那只是

    CONST_NAME = "Name"
    

    下面的代码 sn-p 可能对你有帮助 Link .

    【讨论】:

      猜你喜欢
      • 2021-08-18
      • 2018-07-23
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多