changing local namespace of a function
Michael Spencer
mahs at telcopartners.com
Sat Feb 5 14:07:12 EST 2005
> Alex Martelli wrote:
>> Hmmm, you do realize that wrapdict uses a lot of indirection while my
>> equivalent approach, just posted, is very direct, right? To reiterate
>> the latter, and dress it up nicely too, it's
>>
>> class wrapwell(object):
>> def __init__(self, somedict):
>> self.__dict__ = somedict
>>
Bad mistake on my part, sorry!
Nick Coghlan wrote:
> ... a class that combined property access with the above...
>
In a similar vein to Nick's solution:
class AutoProperty(object):
def __init__(self, meth):
self.meth = meth
self.name = meth.__name__
self.__doc__ = meth.__doc__
def __get__(self, obj, cls):
if isinstance(obj, cls):
return obj.__dict__.setdefault(self.name, self.meth(obj))
else:
return self.__doc__
# You could define __set__ and __del__ but they don't seem
# necessary based on what you've said so far
class DataManipulator(object):
def __init__(self, data):
self.__dict__ = data
class Model(DataManipulator):
def z(self):
"""x+y"""
return self.x+self.y
z = AutoProperty(z)
def z1(self):
"""Or any other useful information"""
return self.z + self.x
z1 = AutoProperty(z1)
# You could automate these calls to AutoProperty in a metaclass
>>> a = {'x':1, 'y':2}
>>> b = {'x':3, 'y':3}
>>> d = Model(a)
>>> d.z
3
>>> d.z1
4
>>> a
{'y': 2, 'x': 1, 'z': 3, 'z1': 4}
>>> d= Model(b)
>>> d.z1
9
>>> b
{'y': 3, 'x': 3, 'z': 6, 'z1': 9}
>>>
Michael
More information about the Python-list
mailing list