Javatpoint Logo
Javatpoint Logo

Reflection in Python

In this tutorial, we will learn about the reflection mechanism in Python. We will also discuss how to implement the reflection and how it is effective for programming. Let's have a brief introduction to the reflection.

Introduction

The reflection is a mechanism that allows inspecting the attributes of objects that might be passed as a parameter to the function. In other words, reflection is used to increase the dynamic description of the function. For example - When we write the type(obj) then Python will return the type of obj. The reflection helps to write the one recursive reverse function that will work for the iterables like list, string, and another sequence that supports slicing.

The str() method returns the empty string the same as we write ". Likewise, writing a list() is the same thing as writing [].

Let's understand the following example.

Example -

Output:

[40, 30, 20, 10]
tniopTavaJ

Explanation -

While working on a project, a developer writes a lot of classes, and the class has its own functions, and so on. A programmer has control over which class to be used or which function to be called. But sometimes, we need to decide which code to execute based on the user's needs. The user may enter some data, or otherwise, and the reflection passes the user's instruction to run the specific code. This process happens automatically without having to manually check whether the user instruction should execute the piece of code, but the reflection mechanism automatically searches and execute the particular block of code.

Reflection Enabling Functions

Python provides four methods to enables reflection. These functions are -

  • type()
  • isinstance()
  • callable()
  • dir()

Let's understand the above methods.

  • type() - The type() method helps to determine the types of the variable used in the program during runtime. Below is an example of type().

Example -

Output:

<class 'int'>
<class 'str'>
<class 'list'>
  • isinstance() - The isinstance() method takes the two parameters, the first parameter is an object and the second parameter is a class. This method determines if an object is an instance or subclass of the class. Let's understand the following example.

Example -

Output:

is a float: True
is an integer: True
is a string: True
is a tuple: True
is a set: True
is a list: True
is a dict: True
  • callable() - The callable() function determines whether an object is callable. We can make the class callable by using the __call__() method. The callable() function returns True if the object passed appear callable. Let's understand the following example.

Example -

Output:

x is not callable
y is callable
  • dir() - The dir() function returns the list of valid attributes of the object. If the object doesn't have the dir() method, it attempts to find the information from the __dict__(if defined) method. In this case, the list returned from dir() may not be completed. Let's understand the following example.

Example -

Output:

['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
  • getattr() - The getarr() method returns the value of the named attribute of an object. If the attribute does not exist, the function will return the default value that is passed to it. The getattr() function takes three arguments: the object, the name of the attribute, and the default value.

Example -

Output:

"John Doe"
"Unknown"

Explanation -

In the first line, we create an object called obj. In the second line, we use the getattr() function to get the value of the name attribute of obj. The function returns the value of the attribute, which is "John Doe". In the third line, we use the getattr() function to get the value of the age attribute of obj. The function returns the value of the attribute, which is 30. In the fourth line, we use the getattr() function to get the value of the height attribute of obj. The attribute does not exist, so the function returns the default value, which is "Unknown".

Conclusion

Reflection in Python is the ability to inspect and alter the structure and behavior of a program at runtime. This can be used to make code more flexible and dynamic, by allowing it to adapt to different situations, inputs, and outputs. Reflection can also be used to make code more reusable, by allowing it to be used in a variety of ways. We can use reflection to create a function that can be used to operate on any object, regardless of its type.

The reflection is used to create a program that can adapt to different user inputs.

We can use reflection to create a program that can be used to generate different outputs, depending on the situation.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA