
Hence, getattr() function can be used to obtain values of different attributes of a class, object, or module. We can obtain the value of any attribute of the myLaptop object. After that, we have extracted the value of the attribute processor using the getattr() function. Then we have created a Laptop object named myLaptop. Here, we have defined a class Laptop with three attributes namely model, RAM, and processor. Let us understand the working of the getattr() function using the following example.

The ‘ object’ may be a class name, a module name, or an instance of a class.The syntax for the getattr() function is as follows. In python, the getattr() function is used to extract the value of an attribute from a class or a module using its name. String To Function Using The getattr() Function In Python Hence, we have converted a string to a function in python, Given that a function with the name of the given string is already defined. After that printTenNumbers() is executed and the numbers are printed. The eval() function first calculated the expression ‘‘ printTenNumbers + “()”’ to ‘ printTenNumbers()’. ‘ printTenNumbers’ and ‘ ()’ separated by + sign to the eval() function. Here, we have declared a function named ‘ printTenNumbers’ that prints the numbers from 1 to 10. For instance, we can evaluate a mathematical expression using the eval() function as follows.

The eval() function takes a string expression as input, parses it, and returns the output after evaluating the input expression. But, have you ever tried to convert a string to a function given that a function with the same name has been defined in a different module or class? In this article, we will discuss how we can convert string to function call using different ways in python String To Function Using The eval() Function In Python We also use different functions in our program. Strings are one of the most used data structures when we process text data. String To Function Using The getattr() Function And Class Instance.String To Function Using The getattr() Function And Class Name.

String To Function Using The getattr() Function And Module Name.String To Function Using The getattr() Function In Python.String To Function Using The eval() Function In Python.
