在Python中正确使用全局变量3 [英] Correct Use Of Global Variables In Python 3

查看:145
本文介绍了在Python中正确使用全局变量3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



1)陈述全局VAR_NAME 一次在核心脚本中(不在函数中),然后在其他地方简单地引用变量 VAR_NAME

2 )在每个使用全局变量的函数中声明全局VAR_NAME ,然后简单地将变量作为 VAR_NAME 在核心脚本本身中的其余部分

解决方案

在第一种情况下,全局关键字是毫无意义的,所以这是不正确的。在模块级定义一个变量使其成为一个全局变量,不需要全局关键字。



第二个例子是正确的用法。

然而,全局变量的最常见用法是不在任何地方使用全局关键字。仅当您想要重新分配函数/方法中的全局变量时,才需要全局关键字。

Which is the correct use of global variables in Python 3?:

1) Stating global VAR_NAME once in the core script (not within a function) and then simply referring to the variable as VAR_NAME everywhere else

2) Stating global VAR_NAME once within every function that uses the global variable and then simply referring to the variable as VAR_NAME for the rest of the function and within the core script itself

解决方案

In the first case the global keyword is pointless, so that is not correct. Defining a variable on the module level makes it a global variable, you don't need to global keyword.

The second example is correct usage.

However, the most common usage for global variables are without using the global keyword anywhere. The global keyword is needed only if you want to reassign the global variables in the function/method.

这篇关于在Python中正确使用全局变量3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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