fork download
  1. class instanceable_classmethod(classmethod):
  2. def __init__(self, func):
  3. super().__init__(func)
  4. self.instance_func = self.__func__
  5.  
  6. def instancemethod(self, func):
  7. self.instance_func = func
  8. return self
  9.  
  10. def __get__(self, obj, cls=None):
  11. if obj is None:
  12. return super().__get__(obj, cls)
  13. return self.instance_func.__get__(obj)
  14.  
  15.  
  16. class Foo(object):
  17. def __init__(self, text):
  18. self.text = text
  19.  
  20. @instanceable_classmethod
  21. def bar(cls):
  22. return None
  23.  
  24. @bar.instancemethod
  25. def bar(self):
  26. return self.text
  27.  
  28. print(Foo.bar()) # outputs None
  29. foo = Foo('foo')
  30. print(foo.bar()) # outputs foo
Success #stdin #stdout 0.11s 14152KB
stdin
Standard input is empty
stdout
None
foo