python - 在 Python 类中声明全局变量

标签 python python-2.7

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

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

class UserPage(webapp2.RequestHandler):
    #i want to access myvariable in this class

最佳答案

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

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

    def get(self):
        HomePage.myvariable = "content"

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

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

class HomePage(webapp2.RequestHandler):
    def get(self):
        self.myvariable = "content"

关于python - 在 Python 类中声明全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20951130/

相关文章:

python - 访问列表推导中的先验元素

python - Python 中的 RTD 客户端

Python:将参数传递给 threading.Thread 实例的正确方法是什么

python - 为什么我得到 'list' object has no attribute 'items' ?

python - 安装 asyncio 向后移植 trollius 时出现 gcc 错误(Python 2.7.5 和 Win7)

python - 如何使这个 Python 代码块简短而高效

Python/Django AMQP?

python - 我的新行回显命令不起作用

ubuntu - 在 Ubuntu 上,如何通过 apt-get 安装 pygtk for python 2.7?

python - 如何创建一个总结多个日常资料的情节?