python中用于定义全局变量的null等效项

2024-04-18 20:16:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一个用Python创建全局变量的示例,就像在java中一样

 String my_global_string = null
 for .... {
     reassign value of my_global_string
}
use the my_global_string value 

如果对象的类型为file,那么在python中null的等价物是什么


Tags: ofthe对象示例forstringvalueuse
1条回答
网友
1楼 · 发布于 2024-04-18 20:16:08

仔细看,这个问题似乎不是关于None,而是关于范围。Python没有块作用域,因此,只要循环本身处于全局作用域,您分配给循环内my_global_string的任何定义都可以用作初始定义

在进入循环之前,无需对名称“预先指定”空值(None

for x in some_iterable:
    my_global_string = "hi there"

print(my_global_string)

如果需要从其他作用域定义全局,这就是global语句存在的原因

# This function creates a variable named "my_global_string"
# in the global scope.
def define_a_string():
    global my_global_string
    my_global_string = "hi there"

for x in some_iterable:
    define_a_string()

print(my_global_string)

相关问题 更多 >