Search code examples
pythonclassattributes

Chained attributes


Is there a way to make a python class such that,

a = Foo()
a.user.details.money.pay = 130000
print(a.user.details.money.pay)

outputs 130000

If possible, could you also explain the class?


Solution

  • Python calls __getattr__ when it can't find an attribute on an object. Your class could use that to assign a new instance of itself to the attribute. Now you have a named attribute that will play the same game for the next attribute down the line.

    class Foo:
    
        def __getattr__(self, name):
            setattr(self, name, foo:=Foo())
            return foo
    
    
    a = Foo()
    a.user.details.money.pay = 130000
    print(a.user.details.money.pay)
    

    Here, a.__getattr__ creates user, a.user.__getattr__ creates details, and etc. Since this is an assignment operation, that last component, pay, is a __setattr__ operation, not a __getattr__, so your custom getter doesn't run.

    This can mask bugs as this class will create unintended attributes as well.