I have a class like:
class MyClass:
Foo = 1
Bar = 2
Whenever MyClass.Foo or MyClass.Bar is invoked, I need a custom method to be invoked before the value is returned. Is it possible in Python? I know it is possible if I create an instance of the class and I can define my own __getattr__ method. But my scnenario involves using this class as such without creating any instance of it.
Also I need a custom __str__ method to be invoked when str(MyClass.Foo) is invoked. Does Python provide such an option?
__getattr__()and__str__()for an object are found on its class, so if you want to customize those things for a class, you need the class-of-a-class. A metaclass.printing:
And no, an object can’t intercept a request for a stringifying one of its attributes. The object returned for the attribute must define its own
__str__()behavior.Updated 2023-02-20 for Python 3.x default implementation (python 2 as a comment).