Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Global variable in Python Class

How do i declare global variable in python class. What i mean is : if i have a class like this

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

class UserPage(webapp2.RequestHandler):
    #i want to access myvariable in this class
like image 639
Nosakhare Belvi Avatar asked Jan 06 '14 13:01

Nosakhare Belvi


2 Answers

You can also use class variables for this, which are a bit cleaner solution than globals:

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

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

You can access it with HomePage.myvariable again from other classes also.

To create an ordinary instance variable use this:

class HomePage(webapp2.RequestHandler):
    def get(self):
        self.myvariable = "content"
like image 187
BartoszKP Avatar answered Oct 12 '22 23:10

BartoszKP


Declare the variable global wherever you assign it

myvariable = None

class HomePage(webapp2.RequestHandler):
   def get(self):
       global myvariable
       myvariable = "content"
like image 27
Eric Avatar answered Oct 13 '22 00:10

Eric