Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create attributes dynamically in python?

Tags:

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

like image 859
Lingfeng Xiong Avatar asked Jan 24 '26 18:01

Lingfeng Xiong


1 Answers

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()
like image 91
onlytiancai Avatar answered Jan 26 '26 08:01

onlytiancai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!