I have a class who's fields are an instance of another class.
class Field:
def get(self):
def set(self, value):
def delete(self):
class Document:
def __init__(self):
self.y = Field()
self.z = True
What I'd like to be able to do is when an instance of the parent refers to its attributes, instead it calls the child's methods.
d = Document()
d.y = 'some value' # Calls the `set` function of the Field
d.y == 'some value' # Calls the `get` function of the Field
del d.y # Calls the `delete` function of the Field
The other catch is that I only want this behavior when the field is of type Field
.
I'm running into recursion problems try to use __getattr__
and the like, along the lines of:
def __getattr__(self, key):
if isinstance(getattr(self, key), Field):
return getattr(self, key).get()
return getattr(self, key)
The recursion is fairly obvious why its happening... but how do I avoid it?
I've seen a few examples already on StackOverflow, but I can't seem to figure out how to get around it.