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
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
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
why not hasattr ?
ReplyDeletehasattr also work for checking attribute exist in a object.
ReplyDeleteit just that i kinda like the dict convention, one less function to remember.
also, it is nice to generate out a list of attribute that we created in a objects like obj.val = 'val'
dir(obj) lists all attributes including functions.
ReplyDeletechecking attribute existence __dict__ is so not pythonic.
Enlightened i am.
ReplyDeleteafter read the doc, dir is a better idea....