简体   繁体   English

在函数中使用另一个函数的变量

[英]Using variables from another function in a function

I have tried to search this but I don't quite understand. 我尝试搜索此内容,但我不太了解。 I am coming across this error so I formed a quick easy example. 我遇到了这个错误,因此我举了一个简单的例子。

def test():
    global a
    a = 0
    a+=1

def test2():
    a+=1
    print (a)


inp = input('a?')
if inp == 'a':
    test()
    test2()

When I input a . 当我输入a I expected the code to output 2. However, I get this error UnboundLocalError: local variable 'a' referenced before assignment . 我希望代码输出2。但是,出现此错误UnboundLocalError: local variable 'a' referenced before assignment When I searched around about this, I found that you need to use global , but I already am using it. 当我四处搜索时,我发现您需要使用global ,但是我已经在使用它了。

So I don't understand. 所以我不明白。 Can someone briefly explain what I'm doing wrong? 有人可以简要说明我在做什么吗? Thanks. 谢谢。

A global declaration only applies within that function. global声明仅适用于该函数。 So the declaration in test() means that uses of the variable a in that function will refer to the global variable. 因此, test()的声明意味着该函数中变量a使用将引用全局变量。 It doesn't have any effect on other functions, so if test2 also wants to access the global variable, you need the same declaration there as well. 它对其他函数没有任何影响,因此,如果test2也想要访问全局变量,则也需要在其中声明相同的内容。

def test2():
    global a
    a += 1
    print(a)

1) You can return the modified value like: 1)您可以返回修改后的值,例如:

def test():
    a = 0
    a+=1
    return a

def test2(a):
    a+=1
    print (a)


inp = input('a?')
if inp == 'a':
    a = test()
    test2(a)

2) Or you can use a class: 2)或者您可以使用一个类:

class TestClass:

    a = 0

    def test(self):
        self.a = 0
        self.a+=1

    def test2(self):
        self.a+=1
        print (self.a)

Usage of option 2: 选项2的用法

>>> example = TestClass()
>>> example.test()
>>> example.test2()
2

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

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