I have a python object with several attributes and methods. I want to iterate over object attributes.
class my_python_obj(object):
attr1='a'
attr2='b'
attr3='c'
def method1(self, etc, etc):
#Statements
I want to generate a dictionary containing all of the objects attributes and their current values, but I want to do it in a dynamic way (so if later I add another attribute I don’t have to remember to update my function as well).
In php variables can be used as keys, but objects in python are unsuscriptable and if I use the dot notation for this it creates a new attribute with the name of my var, which is not my intent.
Just to make things clearer:
def to_dict(self):
'''this is what I already have'''
d={}
d["attr1"]= self.attr1
d["attr2"]= self.attr2
d["attr3"]= self.attr3
return d
·
def to_dict(self):
'''this is what I want to do'''
d={}
for v in my_python_obj.attributes:
d[v] = self.v
return d
Update:
With attributes I mean only the variables of this object, not the methods.
Assuming you have a class such as
calling
diron the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.You can always filter out the special methods by using a list comprehension.
or if you prefer map/filters.
If you want to filter out the methods, you can use the builtin
callableas a check.You could also inspect the difference between your class and its instance object using.