self

holger krekel pyth at devel.trillke.net
Wed Jun 5 20:28:15 EDT 2002


Vojin Jovanovic wrote:
> [me]
> > The next best solution IMO is to preprend a namescope like 'self.'
> > to every name in an expression.
> > But you may have to parse the expression to
> > do this.
> 
> I have been thinking about this for some time, and realized that there some
> tricky cases that one has to deal with, and I am not sure that the whole
> business of appending self. will be error free in every case. 
> For example in 'x + Geometry.x' the correct result should
> be 'self.x + self.Geometry.x' where Geometry is an instance of Geometry
> class that is bound to self.Geometry.

with a small modification to my previously posted class you *can* do this:

class Evaluator:
    def __init__(self, eqs={}):
        self.__dict__['equations']=eqs
    def __getattr__(self, name):
        value = self.equations[name]
        if type(value)!=str:
            return value   # if it's not a string, just give it back
        scope={}
        while 1:
            try:
                return eval(value, scope)
            except Namerror, n:
                var=str(n).split("'")[1]
                scope[var]=getattr(self, var)
    def __setattr__(self, name, value):
        self.equations[name]=value

class Berta:
    a=5

>>> e=Evaluator({'a':'3'])
>>> e.berta=Berta()
>>> e.g='berta.a*a'
>>> e.g
15

This is hopefully what you want. This version doesn't detect 
cycles in equation definitions, though. Shouldn't be too difficult 
to add but requires some more thought. ask again if you
are having problems with it.

have fun,

    holger





More information about the Python-list mailing list