self
Nicola Kluge
NKluge at optonline.net
Wed Jun 5 01:45:01 EDT 2002
This is an interesting idea. However, your approach doesn't handle the dot
notation.
For example,
If object.x was = to 3 and g was = to 4 I need that
e.f='object.x*g' gives 12.
Just having e=Evaluator({'a':'3', 'b':'a*17', 'c':
'b*a','object.x':'3','g':'4'})
doesn't work. While parsing, 'object.x' is not taken as one symbol in your
approach.
I need to have object capabilities in the equations.
Vojin Jovanovic
"holger krekel" <pyth at devel.trillke.net> wrote in message
news:mailman.1023224648.434.python-list at python.org...
> Vojin Jovanovic wrote:
> > Now let me give you the problem with self which is making my life
> > complicated. Consider this class.
> >
> > class Foo:
> > def __init__(self):
> > self.__dict__['Equations']={
> > 'a':str(5),
> > 'b':'self.a+5',
> > 'c':'self.b*self.a'}
> >
> > (...)
>
> To get rid of 'self' you might like to try this:
>
> class Evaluator:
> def __init__(self, eqs={}):
> self.__dict__['equations']=eqs
> def __getattr__(self, name):
> begin={}
> while 1:
> try:
> return eval(self.equations[name], begin)
> except NameError, n:
> var=str(n).split("'")[1]
> begin[var]=getattr(self, var)
> def __setattr__(self, name, value):
> self.equations[name]=value
>
> >>> e=Evaluator({'a':'3', 'b':'a*17', 'c': 'b*a'})
> >>>
> >>> e.c
> 153
> >>> e.f='a*c'
> >>> e.f
> 459
>
> I don't really think that 'execing' is a good idea here
> but i don't know your complete usecase.
>
> With a little more care it should be possible to
> catch cyclic equations.
>
> have fun,
>
> holger
>
>
More information about the Python-list
mailing list