Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在其他函数中使用全局变量不起作用_Python - Fatal编程技术网

Python 在其他函数中使用全局变量不起作用

Python 在其他函数中使用全局变量不起作用,python,Python,这是我问题的一个简化例子。我需要使用在另一个函数中创建的变量,但是在变量实例化之前放置global不起作用 x = 10 def one(): global x a = x +2 b = a/2 print (b) def two(): one() c = int(input()) def three(): global a global c

这是我问题的一个简化例子。我需要使用在另一个函数中创建的变量,但是在变量实例化之前放置global不起作用

x = 10
def one():
    global x
    a = x +2
    b = a/2
    print (b)
def two():            
    one()             
    c = int(input())            
def three():
    global a
    global c           
    d = c + a         
    print(b)

two()         
three()
使用return语句和函数参数:

x = 10
def one(x):
    a = x +2
    b = a/2
    print(b)
    return a, b

def two():                        
    c = int(input()) 
    return c    

def three(a, b, c)                 :         
    d = c + a         
    print(b)

a, b = one(x)
c = two()         
three(a, b, c)

您可以尝试将这三个函数移动到某个类中,在此类中创建一个“x”属性,然后在上述函数中使用此“x”作为self.x。要在Python中使用全局变量,您需要将它们声明为:

x = 10

def one():
    global x
    global a
    global b
    a = x +2
    b = a/2
    print (b)

def two():            
    one()             
    global c
    c = int(input())            

def three():
    global a
    global c           
    d = c + a         
    print(d)
    print(b)

two()       
three()
在Python中,定义在文件顶部的变量(不在函数、if语句等中)被视为全局变量,可以在其他函数等中访问整个文件,也可以访问导入该文件的任何文件

在非主体范围内定义的变量表示函数,该函数只能访问该变量。在这种情况下,如果在主体之外的主体中定义了一个新变量,则需要在创建变量之前告诉Python该变量是全局变量。类似地,如果需要访问全局变量,则需要在尝试访问它之前使用全局变量


这不是最好的实现。与其他人一样,我建议使用带有参数和返回的类或函数。

如果您从函数返回值,则可以在函数本身之外使用它。如果您希望这些变量是全局变量,则应将它们设置为全局变量-在外部范围中定义它们。重复:非常感谢。你真的帮了我。祝您有个美好的一天。