How do you check whether a python method is bound or not?

后端 未结 5 1105
醉话见心
醉话见心 2020-12-15 02:54

Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it\'s bound to?

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-15 03:30

    The chosen answer is valid in almost all cases. However when checking if a method is bound in a decorator using chosen answer, the check will fail. Consider this example decorator and method:

    def my_decorator(*decorator_args, **decorator_kwargs):
        def decorate(f):
            print(hasattr(f, '__self__'))
            @wraps(f)
            def wrap(*args, **kwargs):
                return f(*args, **kwargs)
            return wrap
        return decorate
    
    class test_class(object):
        @my_decorator()
        def test_method(self, *some_params):
            pass
    

    The print statement in decorator will print False. In this case I can't find any other way but to check function parameters using their argument names and look for one named self. This is also not guarantied to work flawlessly because the first argument of a method is not forced to be named self and can have any other name.

    import inspect
    
    def is_bounded(function):
        params = inspect.signature(function).parameters
        return params.get('self', None) is not None
    

提交回复
热议问题