So being lazy, I use the __dict__ special attribute. It exist in every python object, and contains symbol tables of the object, which I can use to check for existence of a attribute. For example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
>>> s = Sample() | |
>>> s.__dict__ | |
{'test_val':1,'another_val':'a'} | |
>>> 'test_val' in s.__dict__ | |
True | |
""" | |
class Sample: | |
def __init__(self): | |
self.test_val = 1 | |
self.another_val = 'a' |
so we can do thing like check a item like 'test_val' in c.__dict__ to check for a existence of a attribute.
From the same idea, one very cool thing to do is, convert get the __dict__ and convert the attribute into a json object, with example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
""" | |
>>> c = C() | |
>>> c.a = 1 | |
>>> c.b = 2 | |
>>> c.__dict__ | |
{'a':1,'b':2} | |
>>> c.to_json() | |
'{"a":1,"b":2}' | |
>>> json.dumps(c.__dict__) | |
'{"a":1,"b":2}' | |
""" | |
class C: | |
def to_json(self): | |
json.dumps(self.__dict__) |
One idea I have been playing is, because django model instance is essentially a objects, we can use the same idea, to output the value in a single django model instance into a json string, but we need to be careful on certain data type like double etc.
The big catch is of using this is, __dict__ only contains attributes of a objects, it does not contain built-in attributes, and it does not contain methods. So if a value is from a method, you need to think of another way. Which actually sucks, as I have a lot of such methods in my classes, well I probably figure out by that time.
So, happy coding