Wrapping classes
Diez B. Roggisch
deets at nospam.web.de
Fri Sep 23 06:20:46 EDT 2005
Jeremy Sanders wrote:
> Peter Hansen wrote:
>
>
>>Almost anything is possible in Python, though whether the underlying
>>design idea is sound is a completely different question. (Translation:
>>try the following pseudo-code, but I have my suspicions about whether
>>what you're doing is a good idea. :-) )
>
>
> What I'd like to do precisely is to be able to evaluate an expression like
> "a+2*b" (using eval) where a and b are objects which behave like numarray
> arrays, but whose values aren't computed until their used.
Maybe you can do that by passing eval your own globals dictionary -
which in its __getitem__ method will then compute the value lazy.
The heck, we're in python. Lets try:
class Foo(object):
def __init__(self):
self.a = 10
self.b = 20
#return dict.__new__(self)
def __getitem__(self, key):
print "computing %s" % key
return getattr(self, key)
l = Foo()
print l.a
print eval("10 * a + b", globals(), l)
It works - in python 2.4!! I tried subclassing dict, but my
__getitem__-method wasn't called - most probably because it's a C-type,
but I don't know for sure. Maybe someone can elaborate on that?
Regards,
Diez
More information about the Python-list
mailing list