Chained getattr method calls

68 views Asked by At

let say i have

  class Blah:
    def __init__(self):
       self.foo = ...
       self.bar = ...

foo and bar does NOT implement getattr. And they dont have attr "abc" and "xyz"

Is it possible to trick it to do

  b = Blah()
  x = b.foo.abc
  y = b.bar.xyz

OR

  x = b.abc.foo
  y = b.xyz.bar

foo and bar may not even exists i.e. sort of virtual

1

There are 1 answers

3
Barmar On BEST ANSWER

No, it's not possible. When you do

x = b.foo.abc

it's essentially equivalent to

temp = b.foo
x = temp.abc

When you're using .abc, there's no reference to the Blah instance any more, you're just getting it from whatever value was stored in the foo attribute. So if that value doesn't have an abc attribute or __getattr__ method, you'll get an error.

There's no way for Blah to intercept the access to the next level below its attributes.