Python get all methods in class

How to 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__', ),
.
('add_option', ),
('add_option_group', ),
('add_options', ),
('check_values', ),
('destroy', ),
('disable_interspersed_args',
),
('enable_interspersed_args',
),
('error', ),
('exit', ),
('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__

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

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.

Читайте также:  Can you override static methods in java

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 or inspect.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

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

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)
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

Читайте также:  Соединить несколько html файлов

. 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
([, ],)
, 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())

Источник

Python get all methods in class

Last updated: Feb 21, 2023
Reading time · 3 min

banner

# Table of Contents

# Get all methods of a given class in Python

Use the inspect.getmembers() method to get all methods of a class.

The getmembers() method will return a list containing all of the methods of the class.

Copied!
import inspect class Employee(): def __init__(self, name, salary): self.salary = salary self.name = name def get_name(self): return self.name def get_salary(self): return self.salary # ✅ called inspect.getmembers with the class itself list_of_methods = inspect.getmembers(Employee, predicate=inspect.isfunction) # 👇️ [('__init__', ), ('get_name', ), ('get_salary', )] print(list_of_methods) # ------------------------------------------------------------------ bob = Employee('Bobbyhadz', 100) # ✅ called inspect.getmembers with instance of the class list_of_methods = inspect.getmembers(bob, predicate=inspect.ismethod) # 👇️ [('__init__', >), ('get_name', >), ('get_salary', >)] print(list_of_methods)

We used the inspect.getmembers() method to get a list containing all of the methods of a class.

The inspect.getmembers method takes an object and returns all the members of the object in a list of tuples.

The first element in each tuple is the name of the member and the second is the value.

We set the predicate argument to inspect.function to get a list containing only the methods of the class.

# Passing an instance of the class to inspect.getmembers()

The inspect.getmembers() method can also be passed an instance of a class, but you have to change the predicate to inspect.ismethod .

Copied!
import inspect class Employee(): def __init__(self, name, salary): self.salary = salary self.name = name def get_name(self): return self.name def get_salary(self): return self.salary bob = Employee('Bobbyhadz', 100) list_of_methods = inspect.getmembers(bob, predicate=inspect.ismethod) # [('__init__', >), ('get_name', >), ('get_salary', >)] print(list_of_methods)

The inspect.isfunction predicate returns True if the object is a Python function.

Читайте также:  font-family

The inspect.ismethod predicate returns True if the object is a bound method written in Python.

Make sure to use inspect.isfunction when passing a class to the inspect.getmembers() method and inspect.ismethod when passing an instance to getmembers() .

Alternatively, you can use the dir() function.

# Get all methods of a given class using dir()

This is a three-step process:

  1. Use the dir() function to get a list of the names of the class’s attributes.
  2. Use a list comprehension to filter out the attributes that start with a double underscore and all non-methods.
  3. The list will only contain the class’s methods.
Copied!
class Employee(): def __init__(self, name, salary): self.salary = salary self.name = name def get_name(self): return self.name def get_salary(self): return self.salary class_methods = [method for method in dir(Employee) if not method.startswith('__') and callable(getattr(Employee, method)) ] print(class_methods) # 👉️ ['get_name', 'get_salary']

Filtering out the attributes that start with two underscores is optional.

Make sure to remove the condition if you need to keep method names that start with two underscores.

Copied!
class_methods = [method for method in dir(Employee) if callable(getattr(Employee, method)) ] # ['__class__', '__delattr__', '__dir__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'get_name', 'get_salary'] print(class_methods)

The class_methods list contains all the method names of the class.

# Getting all methods of an instance with dir()

You can also use this approach to get all methods of an instance.

Copied!
class Employee(): def __init__(self, name, salary): self.salary = salary self.name = name def get_name(self): return self.name def get_salary(self): return self.salary bob = Employee('Bobbyhadz', 100) class_methods = [method for method in dir(bob) if not method.startswith('__') and callable(getattr(bob, method)) ] print(class_methods) # 👉️ ['get_name', 'get_salary']

You can use the getattr function if you need to call some of the methods.

Copied!
bob = Employee('Bobbyhadz', 100) class_methods = [method for method in dir(bob) if not method.startswith('__') and callable(getattr(bob, method)) ] print(class_methods) # 👉️ ['get_name', 'get_salary'] method_1 = getattr(bob, class_methods[0]) print(method_1()) # 👉️ Bobbyhadz

The getattr function returns the value of the provided attribute of the object.

The function takes the object, the name of the attribute and a default value for when the attribute doesn’t exist on the object as parameters.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью