Is there any Python object inspector?


In python there is no built−in or normal function that acts as an object inspector. But we can use functions like type(), help(), dir(), vars() or modules like inspect are used to find the attributes, properties and methods of any object.

Also we have other functions like id(), getattr(), hasattr(), globals(), locals(), callable() are useful in looking inside an object to know its attributes and methods. Here we will inspect the objects using some built−in functions. Before that we will create a simple python class and its objects, to refer throughout this article.

Following is the syntax to defing the python class

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54

Using type() function as an object inspector

In python, type() is a built−in function which is used to get type information about an object.

Syntax

type(object, bases, dict) 

Parameters

  • object: Required parameter. If only one parameter is specified, the type() function returns the type of this object

Return Value

This returns a new type class or essentially a metaclass.

Example

Let’s use the above Height class to see how the type() function works as an inspector.

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54
h = Height(2) # Create an object 
print(type(h))

Output

<class '__main__.Height'>

As we create an object h for the Height class and the type() function describes the type of the object h which is height.

Using help() function as an object inspector

The help() is also a python built−in function which is used to get helpful information about an object. Following is the syntax of this function

help(object) 

Example

Again take the Height class, and see how the help() function describes the details of the object.

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54
help(Height)

Output

Help on class Height in module __main__:

class Height(builtins.object)
 |  Height(inches)
 |  
 |  A height class that describes height as inches.
 |  
 |  Methods defined here:
 |  
 |  __init__(self, inches)
 |      Assign the amount of inches to the height object
 |  
 |  tocentimeter(self)
 |      Convert the inches to centimeters.
 |      1 inch = 2.54 centimeter
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:

As we create an object h for the Height class and the type() function describes the type of the object h which is height. Here you can see everything related to the Height() class.

Using the dir() function

The dir() is a built−in function that returns a list which contains all attributes of the object, also it will return the keys included in the __dict__ attribute. Following is the syntax

dir(object)

Parameters

object: Calls attributes of the given object, and it is an optional parameter.

Example

The dir() method returns the list of all existing attributes. At the end of the list we can see attribute “tocentimeter” that we implemented in the class. Also, you can see automatically generated attributes like '__class__', '__delattr__', '__dict__' etc.

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54
print(dir(Height))

Output

['__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__', 'tocentimeter']

Using the hasattr() function

The hasattr() method used to check if an object has a specific attribute or not. Following is the syntax

hasattr(object, name )

Parameters

  • Object: the object for inspection.

  • name: it is a string, name of the specific attribute which we want to check.

  • It returns ‘True’ if the mentioned attribute is present in the object otherwise it will return ‘False’.

Example

Let us see an example

class Height:
    """
    A height class that describes height as inches.
    """
    def __init__(self, inches):
        """
        Assign the amount of inches to the height object
        """
        self.inches = inches
    
    def tocentimeter(self):
        """
        Convert the inches to centimeters.
        1 inch = 2.54 centimeter
        """
        return self.inches * 2.54
h = Height(24)
print(hasattr(h,"tocentimeter"))

Output

True

In the same way we can use the getattr(), id(), and callable() method as object inspectors.

Updated on: 23-Aug-2023

205 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements