2

I want to print "getting x attr" whenever I use the dot notation to get an attribute.

For example

class MyClass:
   my_attribute = "abc"

print(MyClass.my_attribute)

I'd expect it to output like this:

>>> getting my_attribute attr
>>> abc

I'm not instantiating the class. I tried to add a print statement to MyClass.__getattr__() and MyClass.__getattribute__() but none of these will display anything.

I tried the following:

class MyClass:
    def __getattr__(self, key):
        print("running __getattr__")
        return super().__getattr__(key)
    
    def __getattribute__(self, __name: str) -> Any:
        print("running __getattribute__")
        return super().__getattribute__(__name)

    my_attribute = "abc"
  • 1
    Also, be aware you're using the class, not an instance. Perhaps that's intentional, but it will make a difference. – 9769953 Jun 29 '23 at 14:55

1 Answers1

4

MyClass (the class object) is itself an object. You want to define your custom __getattribute__ method on the class that MyClass is an instance of. To do that, use a metaclass:

class MyMeta(type):

    def __getattribute__(self, item):
        print(f"getting {item}")
        return super().__getattribute__(item)


class MyClass(metaclass=MyMeta):
    my_class_attribute = "abc"

then

print(type(MyClass))
print(MyClass.my_class_attribute)

outputs

<class '__main__.MyMeta'>
getting my_class_attribute
abc
Brian61354270
  • 8,690
  • 4
  • 21
  • 43