How to check if python class has a specific method or not?

class C(Test): def __init__(self): print "in C init" super(C, self).__init__() def setup(self): print "\tin C setup" def runtest(self): print "\t\tin C runtest" def teardown(self): print "\t\t\tin C teardown" 

I have such classes in different modules. For example, for class A , B , C , etc. In one module, I consider only classes that have customization and deletion methods. Suppose that class A does not have an installation method, I do not want to consider it for the further part of my program, where I build a list of classes with the installation and launch module. Is there any python function I can use for it? What is the correct way to solve this problem?

+1
source share
3 answers

I would say that this is the case for an abstract base class .

 class Test(metaclass=ABCMeta): @abstractmethod def setup(self): ... @abstractmethod def teardown(self): ... @classmethod def __subclasshook__(cls, C): if cls is Test: if (any("setup" in B.__dict__ for B in C.__mro__) and any("teardown" in B.__dict__ for B in C.__mro___)): return True return NotImplemented 

This defines the type of Test and a __subclasshook__ , which checks whether the class defines setup() and teardown() . This means that any such class will be considered a subclass of Test - that is, issubclass() will return True for issubclass(C, Test) .

Of course, you can simply perform a manual check using the same methodology as the __subclasshook__ function, but abstract base classes provide a good (and standard) way to determine the contract you want to execute.

+2
source

You can use hasattr and callable for the classes themselves (the classes are afterall objects), i.e. something like

 if hasattr( C, 'setup' ) and callable( C.setup ): classes_with_setup.append(C) 

or, in the sense of understanding the list

 classes_with_setup=[ U for U in [A,B,C...] if hasattr(U,'setup') and callable(U.setup)] 

to set up a class list with these features.

This methodology detects inheritance:

 In [1]: class A(object): ...: def f(self): ...: print 'hi' ...: In [2]: class B(A): ...: pass ...: In [3]: hasattr(A,'f') Out[3]: True In [4]: hasattr(B,'f') Out[4]: True In [5]: hasattr(B,'f') and callable(Bf) Out[5]: True 
+1
source

You can use getattr and callable

 setup_method = getattr(your_object, "setup_method", None) if callable(setup_method): setup_method(self.path.parent_op) 

First check to see if the object has an attribute called setup_method , then check that the attribute is a method, and then call it.

0
source

All Articles