This is an advanced version of Python: how to implement __getattr__()?
How do I write a __getattr__
method such that it will be invoked for class attributes (rather than instances of classes)? I tried the obvious
class MyClass:
@classmethod
def __getattr__(cls, name):
if name not in ['attr','attr2']:
raise AttributeError(name=name, obj=cls)
val =f'class {name}'
cls.__setattr__(cls, name, val)
return val
But it didn't work. Specifically, MyClass.attr
returned "type object 'Foo' has no attribute 'attr'", and once I had created an instance of MyClass
, instance.attr
failed with "TypeError: can't apply this setattr to type object"
Background: I have a large number of mechanically generated types which map integers to strings and back again. Most of these classes are not used in any particular invocation of the program, so I want to save space and import time by defining the "forward" dictionary, and then use __getattr__
to generate the "reverse" dictionary on demand.