Lingfeng Xiong
Lingfeng Xiong

Reputation: 1171

How to create attributes dynamically in python?

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

Upvotes: 3

Views: 2263

Answers (4)

user1539038
user1539038

Reputation: 41

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.

Upvotes: 1

onlytiancai
onlytiancai

Reputation: 168

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()

Upvotes: 8

kindall
kindall

Reputation: 184345

Assuming your JSON request returns a Python dictionary:

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

Upvotes: 2

Smashery
Smashery

Reputation: 59683

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)

Upvotes: 7

Related Questions