Search code examples
syntaxattributesnestedgetattr

It is possible to customize the response to nested object attributes?


I'm trying to figure out if there's a way to return one attribute of a nested object when the attribute is addressed using the 'dot' notation, but to return different attributes of that object when subsequent attributes are requested. ex)

class MyAttributeClass:
    def __init__(self, value):
        self.value = value
        from datetime.datetime import now
        self.timestamp = now()

class MyOuterClass:
    def __init__(self, value):
        self._value = MyAttributeClass(value)

test = MyOuterClass(5)


test.value (should return test._value.value)
test.value.timestamp (should return test._value.timestamp)

Is there any way to accomplish this? I imagine, if there is one, it involves defining the __getattr__ method of MyOuterClass, but I've been searching around and I haven't found any way to do this. Is it just impossible? It's not a big deal if it can't be done, but I've wanted to do this many times and I'd just like to know if there's a way.


Solution

  • It seems obvious now, but inheritance was the answer. Defining attributes as instances of a custom class which inherits from the datatype I wanted for ordinary attribute access (i.e. object.attr) and giving this subclass the desired attributes for subsequent attribute requests (i.e. object.attr.subattr).