Python Object with @property's to dict -
i'm new python please excuse if i've glazed on simple this.
i have object this:
class myobject(object):     def __init__(self):         self.attr1 = none         self.attr2 = none      @property     def prop1(self):         return foo.some_func(self.attr1)   and instantiate this:
a = myobject() a.attr1 = 'apple' a.attr2 = 'banana'   and method it's wrapped in expects return of dict, this:
return a.__dict__   but prop1 not included in return. understand why is, it's not in object's __dict__ because holds real attributes.
so question is, how can make return, return this:
{'attr1': 'apple', 'attr2': 'banana', 'prop1': 'modifiedapple'}   other right before return doing:
a.prop1_1 = a.prop1      
you should leave __dict__ be, use attributes live directly on instance.
if need produce dictionary attribute names , values includes property, add property or method produces new dicitonary:
@property def all_attributes(self):     return dict(vars(self), prop1=self.prop1)   this automated introspection detect property objects, take account use properties avoid having calculation up-front in first place; triggering calculations properties may not desirable.
Comments
Post a Comment