简体   繁体   English

在Python中将变量初始化为全局变量与将变量声明为None之间有什么区别?

[英]What is difference between initializing a variable as global and declaring a variable as None in Python

variable= 0

def func():
    global variable #(or variable = None)
    variable = 1

def display():
    print(variable)  

func()
display()

What is the difference between "global variable" or "variable = None" ? “ global variable”或“ variable = None”有什么区别?

I think the major difference is that declaring global will open it's scope to all the functions. 我认为主要区别在于,声明global将打开所有功能的作用域。 But declaring it as None will just initialize an uninitialized variable and creating a new local variable. 但是将其声明为None只会初始化一个未初始化的变量并创建一个新的局部变量。

The default scope of a variable inside a function will be local. 函数内部变量的默认范围将是局部的。 So, when you assign variable = None, you are creating a local variable and assigning none to it. 因此,当您分配变量= None时,您将创建一个局部变量,并且不为其分配任何变量。 Whereas, if you declare it as global, you'll be modifying the global variable that you initialized earlier. 而如果您将其声明为全局变量,则将修改您先前初始化的全局变量。

In python, any global variables initialized outside a function is accessible inside a function. 在python中,在函数外部初始化的所有全局变量都可以在函数内部访问。 However this access is automatic only if you are using it as a read only variable. 但是,仅当您将其用作只读变量时,此访问权限才是自动的。

If you assign to the same name inside a function, a new variable of local scope is created. 如果在函数内分配相同的名称,则会创建一个本地作用域的新变量。 The global keyword tells python that you don't want a local instance, but would like to modify the global variable outside. global关键字告诉python您不需要本地实例,但想在外部修改全局变量。

So in your example func() modifies the global variable and the same variable is accessible from display() in read only mode even without the global keyword. 因此,在您的示例中,func()修改了全局变量,即使没有global关键字,也可以以只读模式从display()访问相同的变量。 However if you assign None to the variable in func() without global keyword, you are creating a new local variable. 但是,如果在不使用global关键字的情况下为func()中的变量分配None,则将创建一个新的局部变量。 Hence in display() you will see the unmodified global variable. 因此,在display()中,您将看到未修改的全局变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM