Extending the 'function' built-in class

alex23 wuwei23 at gmail.com
Mon Dec 2 03:24:10 CET 2013


On 2/12/2013 5:18 AM, G. wrote:
> Hi, I can't figure out how I can extend the 'function' built-in class. I tried:
>    class test(function):
>      def test(self):
>        print("test")
> but I get an error. Is it possible ?

Others have pointed out that you cannot subclass the function type. 
Could you explain what you're trying to achieve? It's possible you could 
use a decorator instead:

     def test(fn):
         def _test():
             print('test')
         fn.test = _test
         return fn

     @test
     def foo():
         pass

     >>> foo.test()
     test

(Note that I've only included _test inside the decorator to show that 
you can create a closure to include the wrapped function, as a way of 
replicating 'self' in your class definition.)



More information about the Python-list mailing list