How to check whether a method exists in Python?

前端 未结 9 1196
栀梦
栀梦 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:24

    Check if class has such method?

    hasattr(Dynamo, key) and callable(getattr(Dynamo, key))
    

    or

    hasattr(Dynamo, 'mymethod') and callable(getattr(Dynamo, 'mymethod'))
    

    You can use self.__class__ instead of Dynamo

    0 讨论(0)
  • 2021-01-30 16:24

    Maybe like this, assuming all method is callable

    app = App(root) # some object call app 
    att = dir(app) #get attr of the object att  #['doc', 'init', 'module', 'button', 'hi_there', 'say_hi']
    
    for i in att: 
        if callable(getattr(app, i)): 
            print 'callable:', i 
        else: 
            print 'not callable:', i
    
    0 讨论(0)
  • 2021-01-30 16:26

    You can try using 'inspect' module:

    import inspect
    def is_method(obj, name):
        return hasattr(obj, name) and inspect.ismethod(getattr(obj, name))
    
    is_method(dyn, 'mymethod')
    
    0 讨论(0)
提交回复
热议问题