Python: can a decorator determine if a function is being defined inside a class?

前端 未结 6 766
Happy的楠姐
Happy的楠姐 2021-02-07 11:58

I\'m writing a decorator, and for various annoying reasons[0] it would be expedient to check if the function it is wrapping is being defined stand-alone or as part of a class (a

6条回答
  •  情歌与酒
    2021-02-07 12:38

    Some hacky solution that I've got:

    import inspect
    
    def my_decorator(f):
        args = inspect.getargspec(f).args
        defined_in_class = bool(args and args[0] == 'self')
        print "%r: %s" %(f, defined_in_class)
    

    But it relays on the presence of self argument in function.

提交回复
热议问题