Python : Assert that variable is instance method?

后端 未结 2 1103
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 13:14

How can one check if a variable is an instance method or not? I\'m using python 2.5.

Something like this:

class Test:
    def method(self):
        p         


        
2条回答
  •  忘掉有多难
    2020-12-03 14:03

    If you want to know if it is precisely an instance method use the following function. (It considers methods that are defined on a metaclass and accessed on a class class methods, although they could also be considered instance methods)

    import types
    def is_instance_method(obj):
        """Checks if an object is a bound method on an instance."""
        if not isinstance(obj, types.MethodType):
            return False # Not a method
        if obj.im_self is None:
            return False # Method is not bound
        if issubclass(obj.im_class, type) or obj.im_class is types.ClassType:
            return False # Method is a classmethod
        return True
    

    Usually checking for that is a bad idea. It is more flexible to be able to use any callable() interchangeably with methods.

提交回复
热议问题