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

后端 未结 5 1110
醉话见心
醉话见心 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:17

    A solution that works for both Python 2 and 3 is tricky.

    Using the package six, one solution could be:

    def is_bound_method(f):
        """Whether f is a bound method"""
        try:
            return six.get_method_self(f) is not None
        except AttributeError:
            return False
    

    In Python 2:

    • A regular function won't have the im_self attribute so six.get_method_self() will raise an AttributeError and this will return False
    • An unbound method will have the im_self attribute set to None so this will return False
    • An bound method will have the im_self attribute set to non-None so this will return True

    In Python 3:

    • A regular function won't have the __self__ attribute so six.get_method_self() will raise an AttributeError and this will return False
    • An unbound method is the same as a regular function so this will return False
    • An bound method will have the __self__ attribute set (to non-None) so this will return True

提交回复
热议问题