I have a Python class that stores some fields and has some properties, like
class A(object):
def __init__(self, x, y):
self.x = x
self.y = y
@property
def z(self):
return self.x+1
What changes do I need to make to the class so that I can do
>>> a = A(1,5)
>>> dict(a)
{'y':5, 'z':2}
where I specify that I want to return y and z? I can’t just use a.__dict__ because it would contain x but not z. I would like to be able to specify anything that can be accessed with __getattribute__.
Add an
__iter__()method to your class that returns an iterator of the object’s items as key-value pairs. Then you can pass your object instance directly to thedict()constructor, as it accepts a sequence of key-value pairs.If you want this to be a little more flexible, and allow the list of attributes to be easily overridden on subclasses (or programmatically) you could store the key list as an attribute of your class:
If you want the dictionary to contain all attributes (including those inherited from parent classes) try:
This excludes members that start with “_” and also callable objects (e.g. classes and functions).