简体   繁体   English

Python 如何在 class 中使用全局变量

[英]Python How can I use global variables in a class

the code:编码:

class ceshi():
    def one(self):
        global a
        a = "i m a"

    def two(self):
        print(a)


if __name__ == '__main__':
    ceshi().two()

error message: NameError: name 'a' is not defined错误消息:NameError:未定义名称“a”

Didn't I define "a"?我没有定义“a”吗? why the error message is 'name "a" is not defind'为什么错误消息是'名称“a”未定义'

You never actually define a .你从来没有真正定义a . Just because you have it within function one does not mean that this function will be called.仅仅因为你在 function 中one它并不意味着这个 function 会被调用。

You should either move a out of the class scope:您应该将a移出 class scope:

 a = "i m a"
 class ceshi():
    def one(self):
        # some other code

    def two(self):
        print(a)

or make a call to one() before calling two() , in order to define a .或在调用two() one() ) ,以定义a

if __name__ == '__main__':
    ceshi().one()
    ceshi().two()
class TestGlobal():
    def one(self):
        global a
        a = "i m a"
    def two(self):
        global a
        print(a)

or you can write this way或者你可以这样写

class TestGlobal():
    global a
    def __init__(self):
        self.a = self.one()
    
    def one(self):
        self.a = "i m a 5"

    def two(self):
        print('------------------>',self.a)

when you defining any variable in class and method then it consider for particular class or method.当您在 class 和方法中定义任何变量时,它会考虑特定的 class 或方法。 So if it is global variable then call it as global first then used it.因此,如果它是全局变量,则首先将其称为全局变量,然后再使用它。

"a" is only defined inside def one() , so you should declare it outside the method scope and later on define its value inside def one() if that's what you want to do. "a" 仅在def one()中定义,因此您应该在方法 scope 之外声明它,然后在def one()中定义它的值,如果您想要这样做的话。 You could just leave it inside def one() but if the method isn't called, it still won't work.你可以把它留在def one()但如果没有调用该方法,它仍然不起作用。

So your code should look like:所以你的代码应该是这样的:

class ceshi():
    global a
    def one(self):       
        a = "i m a"

    def two(self):
        print(a)

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

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