How to check whether a method exists in Python?

前端 未结 9 1377
栀梦
栀梦 2021-01-30 15:53

In the function __getattr__(), if a referred variable is not found then it gives an error. How can I check to see if a variable or method exists as part of an objec

9条回答
  •  梦谈多话
    2021-01-30 16:06

    I use below utility function. It works on lambda, class methods as well as instance methods.

    Utility Method

    def has_method(o, name):
        return callable(getattr(o, name, None))
    

    Example Usage

    Let's define test class

    class MyTest:
      b = 'hello'
      f = lambda x: x
    
      @classmethod
      def fs():
        pass
      def fi(self):
        pass
    

    Now you can try,

    >>> a = MyTest()                                                    
    >>> has_method(a, 'b')                                         
    False                                                          
    >>> has_method(a, 'f')                                         
    True                                                           
    >>> has_method(a, 'fs')                                        
    True                                                           
    >>> has_method(a, 'fi')                                        
    True                                                           
    >>> has_method(a, 'not_exist')                                       
    False                                                          
    

提交回复
热议问题