cPickle and __getattr__
Paul Morrow
pm_mon at yahoo.com
Sun Aug 29 20:33:53 EDT 2004
Chris Curvey wrote:
> Hi all,
>
> I have this program
>
> class Company:
> def __init__(self, revenues, costs):
> self.revenues = revenues
> self.costs = costs
>
> def __getattr__(self, name):
> if name == 'profits':
> return self.revenues - self.costs
>
> c = Company(100, 75)
> print c.revenues
> print c.costs
> print c.profits
>
> import cPickle
> print cPickle.dumps(c)
>
> Everything works fine up until the last line. If I remove the
> __getattr__ function, then everything works (except "print c.profits").
> What is the cPickle class trying to get to that is causing my
> __getattr__ function to be called?
>
> -Chris
>
When you use __getattr__, you should always raise an attribute error for
names that you don't handle.
def __getattr__(self, name):
if name == 'profits':
return self.revenues - self.costs
else:
raise AttributeError, name
Paul
More information about the Python-list
mailing list