Alright, I am rephrasing my question as my motivation wasn't clear enough.
We have a class that users will be populating with properties that are actually implemented using more complex storage/retrieval mechanisms. I've simplified it below. Assume the storage mechanism is just a simple dictionary for now:
class MyClass: def __init__(self, d): self.mydict = d def getterX(self): return self.mydict['X'] def setterX(self, val): self.mydict['X'] = val X = property(getterX, setterX) def getterY(self): return self.mydict['Y'] def setterY(self, val): self.mydict['Y'] = val Y = property(getterY, setterY) da = {} Ma = MyClass(da) Ma.X = 5 Ma.Y = 6 print(Ma.X, Ma.Y) #outputs 5 6 print(da) #outputs {'Y': 6, 'X': 5} This works fine, except its quite error prone and verbose. It requires five lines with no less than 7 instances of X that needs to be cut+paste for each new property. Some of these classes may have dozens of properties.
In lieu of using macros (which I don't think Python supports, and is inefficient), I'm trying to simplify this with some helper functions:
da = {} class MyHelper: def __init__(self, dict, label): self.mydict = dict self.mylabel = label def getter2(self, other): return self.mydict[self.mylabel] def setter2(self, other, value): self.mydict[self.mylabel] = value def makeProperty(d, label): H = MyHelper(d, label) return property(H.getter2, H.setter2) class MyClass: def __init__(self, d): self.mydict = d X = makeProperty(da, 'X') #da is global, but should be self.mydict Y = makeProperty(da, 'Y') # " " " Ma = MyClass(da) Ma.X = 5 Ma.Y = 6 print(Ma.X, Ma.Y) #outputs 5 6 print(da) #outputs {'Y': 6, 'X': 5} Now this almost works, except calls to makeProperty() need to access a global variable da, instead of using self member data.
This is where I'm stuck, but I'm inclined to believe its possible, given the first code example accesses self member data in its getter/setters.
Hopefully this makes things more clear. Thanks, Rob.
Further information:
I think this solution will not work, as it appears the makeProperty calls are only called once, not once per class instantiation as I was assuming.
So is there any way to make this work, or is the user relegated to much cutting + pasting?