How can you get the list of attributes and methods of a object in Python?

There are occasions where having a list of attributes and methods for a Python object becomes helpful for efficient coding and debugging. In this thread, we explore a range of techniques that can assist you in generating a comprehensive list of attributes and methods associated with a Python object.

1. Using "dir()" method:

  • A simple technique involves using the dir() function which returns a list of all attributes and methods of an object.
  • It provides a list containing all attributes and methods created by the user and also lists down all built-in methods available for the object.

2. Using "vars()" method:

  • The vars() function can be used to obtain the attributes and methods associated with an object.
  • To retrieve the methods, vars() can be applied to the class itself, and to retrieve the attributes, it can be applied to the instantiated object.

3. Using "inspect" library:

  • The inspect library contains a function getmembers() which returns a list of attributes and methods associated with an object.
  • It takes the object as an argument and returns a list of tuples, where each tuple represents a member (attribute or method) of the object.
  • In the example code below, the user-defined attributes and methods of the object are filtered separately from all the available methods for that object. We typically only want to view the user-defined attributes or methods instead of viewing all built-in methods.