__getattr__() and __str__() for an object are in its class, so if you want to configure these things for the class, you need the class of the class. Metaclass.
class FooType(type): def _foo_func(cls): return 'foo!' def _bar_func(cls): return 'bar!' def __getattr__(cls, key): if key == 'Foo': return cls._foo_func() elif key == 'Bar': return cls._bar_func() raise AttributeError(key) def __str__(cls): return 'custom str for %s' % (cls.__name__,) class MyClass: __metaclass__ = FooType
print:
foo! bar! custom str for MyClass
And no, an object cannot intercept a request for matching one of its attributes. The object returned for the attribute must define its own __str__() .
Matt Anderson Jul 01 '10 at 6:24 2010-07-01 06:24
source share