Python - 全局变量没有变化

问题描述 投票:-1回答:1

这是我正在做的一个代码的原型,我想访问函数'i()'中的全局变量,但我无法访问它。我想访问函数'i()'中的全局变量,但我无法访问它。谁能帮我解决这个问题?

a = 1

### Uses global because there is no local 'a' 
def f(q): 
    global a
    a = q

def g(q):     
    global a 
    a = q

def h(q):     
    global a 
    a = q

def i(func):
    for j in func:
        j
        global a
        print(a)

### Global scope 
print('global : ',a)
q=1
b = f(q)
q=2
c = g(q)
q=3
d = h(q)
func = [b, c, d]
print(func)
i(func)
print('global : ',a)

輸出

global :  1
[None, None, None]
3
3
3
global :  3
python function global-variables global
1个回答
0
投票
b = f(q)

f(q) 调用函数。b 是函数的返回值,在这种情况下 None. 后来,只是 j 本身在一条线上完全没有作用。你需要做的是 j() 来调用那里的函数。并传递函数本身。f,不 f(). 你不能把 "函数调用 "存储在一个列表中,然后到处传递。当你把 (),得到的只是它的返回值。

为了简单起见,回到你原来的代码中,你调用了 f()q如何将一个函数和参数传递给它是另一个步骤。

© www.soinside.com 2019 - 2024. All rights reserved.