在Python类中声明全局变量

Nos*_*lvi 5 python python-2.7

我如何在python类中声明全局变量。我的意思是:如果我有这样的课程

class HomePage(webapp2.RequestHandler):
   def get(self):
      myvaraible = "content"
     #do something

class UserPage(webapp2.RequestHandler):
    #i want to access myvariable in this class
Run Code Online (Sandbox Code Playgroud)

Bar*_*zKP 6

您还可以为此使用类变量,这是比全局变量更简洁的解决方案:

class HomePage(webapp2.RequestHandler):
    myvariable = ""

    def get(self):
        HomePage.myvariable = "content"
Run Code Online (Sandbox Code Playgroud)

您也可以HomePage.myvariable从其他类再次访问它。

要创建一个普通的实例变量,请使用:

class HomePage(webapp2.RequestHandler):
    def get(self):
        self.myvariable = "content"
Run Code Online (Sandbox Code Playgroud)


Eri*_*ric 5

在分配变量的任何地方声明变量 global

myvariable = None

class HomePage(webapp2.RequestHandler):
   def get(self):
       global myvariable
       myvariable = "content"
Run Code Online (Sandbox Code Playgroud)