Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get list of methods in a Python class?

Tags:

python

I want to iterate through the methods in a class, or handle class or instance objects differently based on the methods present. How do I get a list of class methods?

Also see:

like image 812
Purrell Avatar asked Dec 15 '09 23:12

Purrell


People also ask

How do I check all methods in Python?

You can use the built in dir() function to get a list of all the attributes a module has. Try this at the command line to see how it works. Also, you can use the hasattr(module_name, "attr_name") function to find out if a module has a specific attribute. See the Guide to Python introspection for more information.

How do I get all the functions in a Python module?

We can list down all the functions present in a Python module by simply using the dir() method in the Python shell or in the command prompt shell.


1 Answers

An example (listing the methods of the optparse.OptionParser class):

>>> from optparse import OptionParser >>> import inspect #python2 >>> inspect.getmembers(OptionParser, predicate=inspect.ismethod) [([('__init__', <unbound method OptionParser.__init__>), ...  ('add_option', <unbound method OptionParser.add_option>),  ('add_option_group', <unbound method OptionParser.add_option_group>),  ('add_options', <unbound method OptionParser.add_options>),  ('check_values', <unbound method OptionParser.check_values>),  ('destroy', <unbound method OptionParser.destroy>),  ('disable_interspersed_args',   <unbound method OptionParser.disable_interspersed_args>),  ('enable_interspersed_args',   <unbound method OptionParser.enable_interspersed_args>),  ('error', <unbound method OptionParser.error>),  ('exit', <unbound method OptionParser.exit>),  ('expand_prog_name', <unbound method OptionParser.expand_prog_name>),  ...  ] # python3 >>> inspect.getmembers(OptionParser, predicate=inspect.isfunction) ... 

Notice that getmembers returns a list of 2-tuples. The first item is the name of the member, the second item is the value.

You can also pass an instance to getmembers:

>>> parser = OptionParser() >>> inspect.getmembers(parser, predicate=inspect.ismethod) ... 
like image 147
codeape Avatar answered Oct 01 '22 09:10

codeape