Say there is:
class A(B):
...
where B could be object and ... is not:
@classmethod # or @staticmethod
def c(cls): print 'Hello from c!'
What do I have to do that calling A.c() wont trigger AttributeError?
In other words, I know it is possible to manually add class methods to a class at runtime. But is it possible to do so automatically, say every time a class method is missing it creates some dummy method?
In yet another words, only if I could replace A.__dict__ with my dict which handles __getitem__ – but A.__dict__ seems to be not writable…
You can achieve this by using a
__getattr__hook on a metaclass.Demo:
Note that we set the result of the
classmethodcall straight onto the class, effectively caching it for future lookups.If you need to regenerate the class method on every call instead, use the same method to bind a function to an instance but with the class and metaclass instead (using
cls.__metaclass__to be consistent with metaclass subclassing):For static methods just return the function directly in all cases, no need to muck with the
staticmethoddecorator or the descriptor protocol.