Get the list of methods in a python class

When working with Python classes, it is regularly valuable to recover a list of all the strategies characterized inside a course. This will offer assistance with investigating, documentation, or dynamic method conjuring. In this web journal, we’ll investigate diverse ways to list all the strategies in a Python course with step-by-step code cases.

1. Utilizing dir() Work

The dir() work returns a list of traits and strategies of an protest or course.

class MyClass:
    def method_one(self):
        pass
    
    def method_two(self):
        pass

# Get list of methods and attributes
methods = dir(MyClass)
print(methods)
Output:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'method_one', 'method_two']

This incorporates both user-defined and built-in strategies.

2. Sifting As it were User-Defined Strategies

To urge only user-defined strategies, we are able channel out the extraordinary strategies.

methods = [method for method in dir(MyClass) if callable(getattr(MyClass, method)) and not method.startswith("__")]
print(methods)
Output:
['method_one', 'method_two']

 

3. Utilizing review Module

The review module gives a more organized way to recover lesson strategies.

Illustration:

import inspect

class MyClass:
    def method_one(self):
        pass
    
    def method_two(self):
        pass

methods = [name for name, func in inspect.getmembers(MyClass, predicate=inspect.isfunction)]
print(methods)
Output:
['method_one', 'method_two']

 

4. Posting Strategies of an Occasion

To urge strategies of a lesson occasion, the approach remains the same.

obj = MyClass()
methods = [name for name in dir(obj) if callable(getattr(obj, name)) and not name.startswith("__")]
print(methods)
Output:
['method_one', 'method_two']

 

Conclusion

  • dir() gives a list of all attributes and strategies.
  • Sifting with callable() expels non-method properties.
  • The review module offers a organized way to list strategies.
  • Strategies can be recovered for both classes and occurrences.
  • By utilizing these procedures, you’ll be able viably analyze and control lesson strategies in Python.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top