Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a method exists in Python?

Tags:

python

methods

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

import string import logging  class Dynamo:  def __init__(self,x):   print "In Init def"   self.x=x  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'     else:         raise AttributeError   dyn = Dynamo('1') print dyn.color dyn.color = 'LemonChiffon' print dyn.color dyn.__int__() dyn.mymethod() //How to check whether this exist or not 
like image 890
Rajeev Avatar asked Sep 28 '11 08:09

Rajeev


People also ask

How do I check if a method exists in Python?

In the function __getattr__() , if a referred variable is not found then it gives an error.

What is Getattr Python?

Python | getattr() method Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key. Syntax : getattr(obj, key, def) Parameters : obj : The object whose attributes need to be processed.

How do I see the methods of a class in Python?

To list the methods for this class, one approach is to use the dir() function in Python. The dir() function will return all functions and properties of the class.


2 Answers

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

like image 115
seriyPS Avatar answered Oct 16 '22 05:10

seriyPS


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? 
like image 21
S.Lott Avatar answered Oct 16 '22 07:10

S.Lott