self

holger krekel pyth at devel.trillke.net
Tue Jun 4 17:02:45 EDT 2002


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