Harley Jones
Harley Jones

Reputation: 167

How can I access a variable from another class in python?

I need to access the user_objectid from the LoginScreen class and use it to access that user's high scores for a game using the Parse SDK in the HighScore class. However, I'm not sure how to access this information. Below is my code:

    class LoginScreen(Screen):

       def __init__(self, **kwargs):
          super(LoginScreen, self).__init__(**kwargs)
          self.gametime = BooleanProperty(False)

       _username = ObjectProperty(None)
       _password = ObjectProperty(None)
       user_objectid = ObjectProperty(None)

       def loginUser(self):

          if self._username.text != '' and self._password.text != '':
             try:
                connection = httplib.HTTPSConnection('api.parse.com', 443)
                params = urllib.urlencode({"username":self._username.text,            "password":self._password.text})
                connection.connect()
                connection.request('GET', '/1/login?%s' % params, '', {
                   "X-Parse-Application-Id": "${APPLICATION_ID}",
                   "X-Parse-REST-API-Key": "${REST_API_KEY}",
                   "Content-Type": "application/json"
                })
                result = json.loads(connection.getresponse().read())
                # Confirm valid user
                if result['objectId'] != '':
                   self.user_objectid = result['objectId']
                   return True

This is the code for the HighScore class:

    class HighScore(Screen):
       def __init__(self, **kwargs):
          super(HighScore, self).__init__(**kwargs)

          # Need user_objectid from LoginScreen class here!
          user_id = ObjectProperty()


          connection = httplib.HTTPSConnection('api.parse.com', 443)
          connection.connect()
          connection.request('GET', '/1/classes/GameScore/user_id', '', {
             "X-Parse-Application-Id": "${APPLICATION_ID}",
             "X-Parse-REST-API-Key": "${REST_API_KEY}"
          })
          result = json.loads(connection.getresponse().read())
          print result['score']

Upvotes: 0

Views: 805

Answers (1)

inclement
inclement

Reputation: 29460

First, you twice define properties in the class __init__ functions. This will not give property behaviour, they must be defined at class level for them to work as properties (and not just normal attributes).

For your main question, the answer is simply that your HighScore instance needs a reference to your LoginScreen instance - if it has that, say in the variable lgs, you can simply access lgs.user_objectid to get the value you want.

The best way to do this depends entirely on the structure of your program, and where you create and use those classes and their methods.

Upvotes: 2

Related Questions