- How to find all the methods of a given class in Python?
- Define our template class
- Method 1 – Using the dir() function to list methods in a class
- Filtering dunder methods from the output
- Handling properties of a class
- Method 2 – Using optparse.OptionParser
- Caveats of using the inspect module
- Conclusion
- References
- Списки (list). Функции и методы списков
- Что такое списки?
- Функции и методы списков
- Таблица «методы списков»
How to find all the methods of a given class in Python?
Hello everyone! In today’s article, we’ll take a look at how we can find all the methods of a given class.
Often, it is very convenient to list all the methods of a class directly, so that we can perform some pre-processing based on certain methods.
Let’s get started! We’ll show you some ways to make this happen, and you can use any one of the below methods.
Define our template class
Let’s first define a dummy class, from which we can verify our outputs.
Consider the below class, which has some methods:
class MyClass(object): def __init__(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = a def add(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state + a return self.state def subtract(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state - a return self.state def multiply(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state * a return self.state def divide(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state / a return self.state
The class stores a floating point state attribute, which we can manipulate using arithmetic operations.
Let’s now look at some of the ways to list the methods for our custom class.
Method 1 – Using the dir() function to list methods in a class
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.
Let’s see what happens if we try it for MyClass .
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add', 'divide', 'multiply', 'subtract']
Ok, we can see that we have our add , divide , subtract and multiply methods listed! However, what about all the other methods?
Well, these methods (the ones starting with double underscore) are called dunder methods.
These are usually called by a wrapper function. For example, the dict() function calls the __dict__() method.
Filtering dunder methods from the output
Usually, we won’t be needing the double underscore prefixed methods, so we can filter them using the below snippet:
method_list = [method for method in dir(MyClass) if method.startswith('__') is False] print(method_list)
['add', 'divide', 'multiply', 'subtract']
Wow! We now only get the arithmetic methods that we wanted!
However, our present solution has a problem.
Remember that dir() calls both the methods and the properties of a class?
Handling properties of a class
If we had property inside a class, it would list that too. Consider the below example.
class MyClass(object): # MyClass property property1 = [1, 2, 3] def __init__(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = a def add(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state + a return self.state def subtract(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state - a return self.state def multiply(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state * a return self.state def divide(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state / a return self.state @staticmethod def global_method(a, b): return a + b @classmethod def myclass_method(cls): return cls method_list = [method for method in dir(MyClass) if method.startswith('_') is False] print(method_list)
Now, what do you think the output would be?
['add', 'divide', 'global_method', 'multiply', 'myclass_method', 'property1', 'subtract']
This gives us property1 as well, which is not what we want.
We need to make one more filter to differentiate between a method and a property.
But this is really simple. The main difference is that any property object is NOT callable, while methods can be called!
In Python, we can use the boolean function callable(attribute) to check if the attribute can be called.
Let’s now include this to our old code.
method_list = [attribute for attribute in dir(MyClass) if callable(getattr(MyClass, attribute)) and attribute.startswith('__') is False] print(method_list)
Let’s break it down, by writing it without the list comprehension:
method_list = [] # attribute is a string representing the attribute name for attribute in dir(MyClass): # Get the attribute value attribute_value = getattr(MyClass, attribute) # Check that it is callable if callable(attribute_value): # Filter all dunder (__ prefix) methods if attribute.startswith('__') == False: method_list.append(attribute) print(method_list)
We also changed method to attribute , so that it removes the misleading intention!
['add', 'divide', 'global_method', 'multiply', 'myclass_method', 'subtract']
Indeed, we indeed get our method list, without the properties!
Method 2 – Using optparse.OptionParser
Now, this is another approach you can use, if you’re not too comfortable with using dir() .
We can use the inspect module to list the methods.
Namely, we can use inspect.getmembers(instance, predicate=inspect.ismethod) to get a list of the methods.
This will automatically do the work for you, and you just need to deal with the output. Let’s look at an example.
import inspect class MyClass(object): # MyClass property property1 = [1, 2, 3] def __init__(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = a def add(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state + a return self.state def subtract(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state - a return self.state def multiply(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state * a return self.state def divide(self, a): assert isinstance(a, float) or isinstance(a, int) self.state = self.state / a return self.state @staticmethod def global_method(a, b): return a + b @classmethod def myclass_method(cls): return cls # Create our instance instance = MyClass(100) # Get the list of functions method_list = inspect.getmembers(MyClass, predicate=inspect.ismethod) print(method_list)
[('__init__', >), ('add', >), ('divide', >), ('multiply', >), ('myclass_method', >), ('subtract', >)]
We can get the first element of each tuple, to get the method name.
Caveats of using the inspect module
Notice that we get a list of tuples. The first element of the tuple is the name of the function, which the second element represents the method object itself.
While this may seem to be a good solution, you may notice some things.
- For dir() , we directly used the Class name itself. But here, we need to pass an instance.
- The staticmethods are also not shown in the list. Depending on your use case, you may/may not need it.
Due to the above mentioned points, I would suggest you to stay simple, and use the dir() function!
Conclusion
In this article, we saw how we could list all the methods of a given class in Python.
References
Списки (list). Функции и методы списков
Сегодня я расскажу о таком типе данных, как списки, операциях над ними и методах, о генераторах списков и о применении списков.
Что такое списки?
Списки в Python — упорядоченные изменяемые коллекции объектов произвольных типов (почти как массив, но типы могут отличаться).
Чтобы использовать списки, их нужно создать. Создать список можно несколькими способами. Например, можно обработать любой итерируемый объект (например, строку) встроенной функцией list:
Список можно создать и при помощи литерала:
Как видно из примера, список может содержать любое количество любых объектов (в том числе и вложенные списки), или не содержать ничего.
И еще один способ создать список — это генераторы списков. Генератор списков — способ построить новый список, применяя выражение к каждому элементу последовательности. Генераторы списков очень похожи на цикл for.
Возможна и более сложная конструкция генератора списков:
Но в сложных случаях лучше пользоваться обычным циклом for для генерации списков.
Функции и методы списков
Создать создали, теперь нужно со списком что-то делать. Для списков доступны основные встроенные функции, а также методы списков.
Таблица «методы списков»
Метод | Что делает |
---|---|
list.append(x) | Добавляет элемент в конец списка |
list.extend(L) | Расширяет список list, добавляя в конец все элементы списка L |
list.insert(i, x) | Вставляет на i-ый элемент значение x |
list.remove(x) | Удаляет первый элемент в списке, имеющий значение x. ValueError, если такого элемента не существует |
list.pop([i]) | Удаляет i-ый элемент и возвращает его. Если индекс не указан, удаляется последний элемент |
list.index(x, [start [, end]]) | Возвращает положение первого элемента со значением x (при этом поиск ведется от start до end) |
list.count(x) | Возвращает количество элементов со значением x |
list.sort(List method python object) | Сортирует список на основе функции |
list.reverse() | Разворачивает список |
list.copy() | Поверхностная копия списка |
list.clear() | Очищает список |
Нужно отметить, что методы списков, в отличие от строковых методов, изменяют сам список, а потому результат выполнения не нужно записывать в эту переменную.
И, напоследок, примеры работы со списками:
Изредка, для увеличения производительности, списки заменяют гораздо менее гибкими массивами (хотя в таких случаях обычно используют сторонние библиотеки, например NumPy).
Для вставки кода на Python в комментарий заключайте его в теги
- Книги о Python
- GUI (графический интерфейс пользователя)
- Курсы Python
- Модули
- Новости мира Python
- NumPy
- Обработка данных
- Основы программирования
- Примеры программ
- Типы данных в Python
- Видео
- Python для Web
- Работа для Python-программистов