data strucutures in python
Andrew Dalke
dalke at acm.org
Wed Sep 20 01:30:29 EDT 2000
Matthew Banham:
>I have a list of tuples of the form (variablename, variableFunction).
>In Python, if I type:-
>
>variablename = data then variableFunction gets called with data passed to
>it. For example say I have:-
>
>p = 'lambda', ChangeLambdaFunc
>
>and I type the line:-
>
>lambda = 10
>
>then the above line gets implemented as:-
>
>ChangeLambdaFunc(10)
How about something like the following (untested) code?
_conversions = {
"lambda": ("GetLambdaValue", "ChangeLambdaFunc"),
"readonly": ("GetSomeData", None),
"writeonly": (None, "SetSomeData),
}
class Spam:
def __getattr__(self, name):
funcs = _conversions.get(name)
if funcs is None:
raise AttributeError, name
getter_name = funcs[0]
if getter_name is None:
raise TypeError, "write-only value"
return getattr(self, getter_name)()
def __setattr__(self, name, value):
funcs = _conversions.get(name)
if funcs is None:
self.__dict__[name] = value
else:
setter_name = funcs[1]
if setter_name is None:
raise TypeError, "read-only value"
getattr(self, setter_name)(value)
spam = Spam()
print spam.lambda
print spam.readonly
print spam.writeonly # should give a TypeError
Andrew
dalke at acm.org
More information about the Python-list
mailing list