python中的全局关键字 [英] global keyword in python

查看:54
本文介绍了python中的全局关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究python,并在 vscode 中使用global关键字进行挣扎.到目前为止,代码可以正常工作,但是 vscode 短绒棉引发了错误,我想了解原因

I'm studying python, and getting struggle with the global keyword within vscode. So far the code is working, but the vscode linter is raising an error, and I would like to understand why

我尝试使用global关键字,即使遇到linter错误,代码也可以正常工作.我尝试使用局部变量,但未收到任何错误

I've tried using the global keyword, and the code works fine even though I got a linter error. I try using a local variable and didn't get any error

def whatIs ():
    global myvalue
    myvalue +=10
    print("myvalue: {}".format(myvalue))

myvalue=10

whatIs()

print("myvalue: {}".format(myvalue))

短毛绒指向函数中的 myvalue :

未定义变量'myvalue'pylint(未定义变量)

Undefined variable 'myvalue' pylint(undefined-variable)

但是输出是我期望的.

myvalue: 20
myvalue: 20

这就像 vscode 不喜欢全局关键字

It's like vscode doesn't like the global keyword

推荐答案

尝试移动此行

myvalue=10

在定义WhatIs函数之前.

before the definition of WhatIs function.

myvalue=10

def whatIs ():
    global myvalue
    myvalue +=10
    print("myvalue: {}".format(myvalue))

whatIs()

print("myvalue: {}".format(myvalue))

这篇关于python中的全局关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆