How do I get list of methods in a Python class?
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)
...
Getting all class methods in classes in current file in Python?
On Python 3, calling inspect.ismethod
on an attribute of a class that happens to be a function will always be False, because it will just be a plain function. function.__get__
only returns a method object when accessed as an attribute of an instance.
If you want to get all "methods" of the class just use inspect.isfunction
.
>>> class A:
... def __init__(self): pass
...
>>> A.__init__
<function A.__init__ at 0x7fd524dd2f80>
>>> inspect.ismethod(A.__init__)
False
>>> inspect.isfunction(A.__init__)
True
>>> inspect.ismethod(A().__init__)
True
Finding what methods a Python object has
For many objects, you can use this code, replacing 'object' with the object you're interested in:
object_methods = [method_name for method_name in dir(object)
if callable(getattr(object, method_name))]
I discovered it at diveintopython.net (now archived), that should provide some further details!
If you get an AttributeError
, you can use this instead:
getattr()
is intolerant of pandas style Python 3.6 abstract virtual sub-classes. This code does the same as above and ignores exceptions.
import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
methodList = []
for method_name in dir(object):
try:
if callable(getattr(object, method_name)):
methodList.append(str(method_name))
except Exception:
methodList.append(str(method_name))
processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
for method in methodList:
try:
print(str(method.ljust(spacing)) + ' ' +
processFunc(str(getattr(object, method).__doc__)[0:90]))
except Exception:
print(method.ljust(spacing) + ' ' + ' getattr() failed')
get_methods(df['foo'])
Get a list of class methods inside C-Python
tp_methods
is:
An optional pointer to a static NULL-terminated array of
PyMethodDef
structures, declaring regular methods of this type.For each entry in the array, an entry is added to the type’s dictionary (see
tp_dict
below) containing a method descriptor.This field is not inherited by subtypes (methods are inherited through a different mechanism).
In other words, these are the builtin methods attached to the class by the extension module that created it.
For a class built in Python, there are no builtin methods, and there is no extension module that created it, so it will always be either NULL
or empty.
What you want to do is the same thing you do in Python:
- Either look in the class's dict (which you can access via
tp_dict
), or - Call a method like
dir
orinspect.getmembers
(the same way you'd call any other Python code).
Of course that gets you all attributes of the class (depending on which you do, also possibly all inherited attributes), so if you want just the methods, you need to filter it. But you do this the same way as in Python as well.
Since "method" is kind of an ambiguous term (Should it include classmethods and staticmethods? What about wrappers that act just like functions when bound as methods, but aren't functions? And so on…), you need to come up with exactly the rule you want to filter on, and apply it the same way you would from Python. (A few things, like PyCallable_Check
, have special C API support; for anything else, you'll be doing a subclass check or calling a Python function.)
List all methods of a given class, excluding parent class's methods in Python
Here is a try:
import itertools
from types import FunctionType
def listMethods(cls):
return set(x for x, y in cls.__dict__.items()
if isinstance(y, (FunctionType, classmethod, staticmethod)))
def listParentMethods(cls):
return set(itertools.chain.from_iterable(
listMethods(c).union(listParentMethods(c)) for c in cls.__bases__))
def list_subclass_methods(cls,is_narrow):
methods = listMethods(cls)
if is_narrow:
parentMethods = listParentMethods(cls)
return set(cls for cls in methods if not (cls in parentMethods))
else:
return methods
Explain:
listParentMethods is a recursive function which get the union of the parents' methods.
How to get a list of classes and functions from a python file without importing it
You can use the ast module to parse the source file, without actually executing any code. Then you can traverse the node tree to get the function and class names/parameters.
import ast
def show_info(functionNode):
print("Function name:", functionNode.name)
print("Args:")
for arg in functionNode.args.args:
#import pdb; pdb.set_trace()
print("\tParameter name:", arg.arg)
filename = "untrusted.py"
with open(filename) as file:
node = ast.parse(file.read())
functions = [n for n in node.body if isinstance(n, ast.FunctionDef)]
classes = [n for n in node.body if isinstance(n, ast.ClassDef)]
for function in functions:
show_info(function)
for class_ in classes:
print("Class name:", class_.name)
methods = [n for n in class_.body if isinstance(n, ast.FunctionDef)]
for method in methods:
show_info(method)
Result:
Function name: doStuff
Args:
Parameter name: an_other_arg
Parameter name: an_other_default_arg
Class name: A
Function name: __init__
Args:
Parameter name: self
Parameter name: an_arg
Parameter name: a_default_arg
Get the list of a class's variables & methods in Python
If the class and its superclasses are known, something like:
tuple(set(dir(Foo)) - set(dir(Bar)))
If you want it to be more generic, you can get a list of the base classes using something like
bases = Foo.mro()
...and then use that list to subtract out attributes from all the base classes.
A better way to call Class Methods from List of Class Objects - Python
Assuming you are passing a list of students to the function such as ([<__main__.Student object at 0x122d85990>, <__main__.Student object at 0x122d85910>],)
, you can use :
def show_student_details(*s_list):
for s in s_list[0]:
print("Roll Number: ", s.get_roll_no())
print("Name: ", s.get_name())
print("Phone: ", s.get_phone())
print("Marks: ", s.get_marks())
Because *s_list converts your input to a list. Alternatively, you should be able to just use
def show_student_details(s_list):
for s in s_list:
print("Roll Number: ", s.get_roll_no())
print("Name: ", s.get_name())
print("Phone: ", s.get_phone())
print("Marks: ", s.get_marks())
Related Topics
Pandas: Drop a Level from a Multi-Level Column Index
Difference Between Variables Inside and Outside of _Init_()
How to "Test" Nonetype in Python
Why Isn't My Pandas 'Apply' Function Referencing Multiple Columns Working
Access an Arbitrary Element in a Dictionary in Python
Error: Command 'Gcc' Failed with Exit Status 1 While Installing Eventlet
Scraping: Ssl: Certificate_Verify_Failed Error for Http://En.Wikipedia.Org
Python Functions Call by Reference
Combine Several Images Horizontally with Python
Case Insensitive Regular Expression Without Re.Compile
Send File Using Post from a Python Script
Python Date String to Date Object
Django Set Default Form Values
Replace All Elements of Python Numpy Array That Are Greater Than Some Value
How to Activate an Anaconda Environment