cPickle problem
Vojin Jovanovic
vjovanov at stevens-tech.edu
Tue Apr 30 17:15:50 EDT 2002
Thanks, I understand this a bit better. I changed my implementation of foo
like this
>>> class foo:
def __init__(self):
self.y=4
self.e={'a':'self.y',
'b':'self.a+4'}
def __getattr__(self,arg):
if self.e.has_key(arg) == 0:
raise AttributeError, "foo instance has no attribute '" + arg + "'"
try:
exec 'result =' + self.e[arg]
return result
except:
return '#U'
def addequation(self,attr,value):
self.e[attr] = value
>>> k=foo()
>>> k.e
{'b': 'self.a+4', 'a': 'self.y'}
>>> k.a
4
>>> k.b
8
>>> k.ddd
Traceback (most recent call last):
File "<pyshell#121>", line 1, in ?
k.ddd
File "<pyshell#105>", line 8, in __getattr__
raise AttributeError, "foo instance has no attribute '" + arg + "'"
AttributeError: foo instance has no attribute 'ddd'
As you can see I added a new method 'addequation' that works like this
>>> k.addequation('c','self.a+self.b')
>>> k.e
{'b': 'self.a+4', 'c': 'self.a+self.b', 'a': 'self.y'}
>>> k.c
12
and now I have another question.
can I replace addequation with __setattr__ so that I can type
>>>k.c='self.a+self.b'
to achieve the same effect.
>>> k.e
{'b': 'self.a+4', 'c': 'self.a+self.b', 'a': 'self.y'}
>>> k.c
12
My attempts with __setattr__ were unsuccessful.
Thanks for you help
Vin
More information about the Python-list
mailing list