Python函数全局变量?

2024-03-28 18:41:37 发布

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

我知道我应该首先避免使用全局变量,因为这样的混乱,但是如果我要使用它们,下面是使用它们的有效方法吗?(我试图调用在单独函数中创建的变量的全局副本。)

x = "somevalue"

def func_A ():
   global x
   # Do things to x
   return x

def func_B():
   x=func_A()
   # Do things
   return x

func_A()
func_B()

第二个函数使用的“x”是否与“func_a”使用和修改的“x”的全局副本具有相同的值?在定义后调用函数时,顺序是否重要?


Tags: to方法函数return定义def副本全局
1条回答
网友
1楼 · 发布于 2024-03-28 18:41:37

正如其他人所指出的,如果希望函数能够修改全局变量,则需要在函数中声明变量global。如果您只想访问它,则不需要global

更详细地说,“modify”的意思是:如果要重新绑定全局名称,使其指向不同的对象,则必须在函数中声明名称global

许多修改(变异)对象的操作不会重新绑定全局名称以指向不同的对象,因此它们都是有效的,而无需在函数中声明名称global

d = {}
l = []
o = type("object", (object,), {})()

def valid():     # these are all valid without declaring any names global!
   d[0] = 1      # changes what's in d, but d still points to the same object
   d[0] += 1     # ditto
   d.clear()     # ditto! d is now empty but it`s still the same object!
   l.append(0)   # l is still the same list but has an additional member
   o.test = 1    # creating new attribute on o, but o is still the same object

相关问题 更多 >