How to check whether a method exists in Python?

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

    It's easier to ask forgiveness than to ask permission.

    Don't check to see if a method exists. Don't waste a single line of code on "checking"

    try:
        dyn.mymethod() # How to check whether this exists or not
        # Method exists and was used.  
    except AttributeError:
        # Method does not exist; What now?
    

提交回复
热议问题