【问题标题】:VSCode is saying variables which use change using += 1 in python should be constants. Is this correct?VSCode 说在 python 中使用 += 1 进行更改的变量应该是常量。它是否正确?
【发布时间】:2021-03-12 03:39:02
【问题描述】:

下面是我的代码的一个极其简化的版本:

foo = 0
bar = 0
baz = 0
while True:
    answer = input('Type an input here: ')
    print('And do something with it here.')
    if answer == 'okay':
        foo += 1
    else:
        bar += 1
    baz += 1
    print(foo, bar, baz)

当我保存这个时,VSCode 给我一个警告说:

常量名称“foo”不符合 UPPER_CASE 命名风格

常量名称“foo”不符合 UPPER_CASE 命名风格

常量名称“foo”不符合 UPPER_CASE 命名风格

我的问题是“+= 1”是否会影响变量是否应该是常量?我认为“+= 1”会导致变量在变量更改时不是常量,但 VSCode 告诉我不是这样。

【问题讨论】:

标签: python python-3.x visual-studio-code constants


【解决方案1】:

我重现了这个问题:

原因:根据official pylint documentation的描述,出现这个警告的原因是Pylint默认的常量命名风格是大写的:

"Naming style matching correct constant names.
Default: UPPER_CASE"

因此,针对“foo = 0bar = 0baz = 0”和“foo += 1bar += 1baz += 1”检查 Pylint 的警告,Pylint 不给出警告,Pylint 将它们作为变量检查.

解决方法:使用默认大写名称:FOO,BAR,BAZ。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 2016-10-12
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多