Rajeev Rajeev - 1 year ago 120
Python Question

How to check whether a method exists in Python?

In the function

, 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 object?

import string
import logging

class Dynamo:
def __init__(self,x):
print "In Init def"
def __repr__(self):
print self.x
def __str__(self):
print self.x
def __int__(self):
print "In Init def"
def __getattr__(self, key):
print "In getattr"
if key == 'color':
return 'PapayaWhip'
raise AttributeError

dyn = Dynamo('1')
print dyn.color
dyn.color = 'LemonChiffon'
print dyn.color
dyn.mymethod() //How to check whether this exist or not

Answer Source

How about dir() function before getattr()?

>>> "mymethod" in dir(dyn)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download