3

I have a class like this:

class User:
    def __init__(self, uid):
        userinfo = json.load(urlopen(passportapi + 'user/' + uid))

This class would load user information from a remote api and set corresponding attributes for this class so I can access these attributes by:

print user.username
print user.group_id

Is there any way to implement this? Thanks

4
  • Which part are you having trouble with? Commented Sep 12, 2012 at 1:16
  • I have no idea how to write the code for this class to allow me access it's attributes like 'print user.username' Commented Sep 12, 2012 at 1:24
  • How about this? print vars(user)['username'] You can replace 'username' with the name of any attribute you want to access Commented Sep 12, 2012 at 1:25
  • I believe Smashery's answer is more suitable for my problem :-) Just need to write his code in __init__(self) and everything works well. :-) Commented Sep 12, 2012 at 1:31

4 Answers 4

8
import json

api_result = '{"username":"wawa","age":20}'

class User(object):
    def __init__(self, api_result):
        userinfo = json.loads(api_result)
        self.__dict__.update(userinfo)

import unittest

class DefaultTestCase(unittest.TestCase):
    def test_default(self):
        user = User(api_result)
        self.assertEqual(user.username, 'wawa')
        self.assertEqual(user.age, 20)

if __name__ == '__main__':
    unittest.main()
Sign up to request clarification or add additional context in comments.

1 Comment

This is the most complete answer :-) Thank you.
7

You can do this sort of thing using the setattr function:

>>> class A(object):
    pass
>>> a = A()
>>> setattr(a, 'val', 4)
>>> a.val
4

In your case, assuming your parsed json file provides some sort of key-value pair (like a dict), you can just iterate through those, and call setattr on self; something like this (assuming userinfo is a dict):

class User:
    def __init__(self, uid):
        userinfo = json.load(urlopen(passportapi + 'user/' + uid))
        for key, value in userinfo.iteritems():
            setattr(self, key, value)

Comments

2

Assuming your JSON request returns a Python dictionary:

class User:
    def __init__(self, uid):
        self.__dict__.update(json.load(urlopen(passportapi + 'user/' + uid)))

Comments

1

Sometimes I like to have a little more encapsulation and control than what 'update' would offer. I would probably accomplish what you are trying to do like this:

class User(object):                                                             
    def __init__(self, api_result):                                             
        self.userinfo = json.loads(api_result)                                  

    def __getattr__(self, name):                                                
        if name in self.userinfo: return self.userinfo[name]                    
        raise AttributeError 

I think this method will allow you to do other things like filter certain keywords and raise custom exceptions for accessing your data.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.