Belvi Nosakhare
Belvi Nosakhare

Reputation: 3255

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

Upvotes: 8

Views: 10765

Answers (2)

BartoszKP
BartoszKP

Reputation: 35891

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"

Upvotes: 7

Eric
Eric

Reputation: 97555

Declare the variable global wherever you assign it

myvariable = None

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

Upvotes: 5

Related Questions