Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Explicitly define datatype in a Python function
Next article icon

In this article, we will see how to call a function of a module by using its name (a string) inPython. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between start(inclusive) and end(inclusive). Here, we will discuss 2 methods to solve this:

  • Python Getattr() Method
  • Python exec() Method

What is Getattr() Method

Python getattr() function is used to access the attribute value of an object and also gives an option of executing the default value in case of unavailability of the key.

Syntax of getattr() method

Syntax: getattr(obj, key, def)

  • obj: The object whose attributes need to be processed.
  • key: The attribute of object
  • def: The default value that needs to be printed in case the attribute is not found.

Returns: Object value if the value is available, the default value in case attribute is not present, and returns AttributeError in case attribute is not present and the default value is not specified.

Example 1

Importing a module random and using getattr() method to access randint method of random.

Python3
if__name__=="__main__":# Importing a module randomimportrandom# Using randint function of random# module as rr=getattr(random,'randint')# calling the function and storing# the value in resres=r(1,9)# Printing the resultprint(res)

Output:

9

Example 2

Here, we are using randint function of the random module as func.

Python3
if__name__=="__main__":# Importing a module randomModule=__import__('random')func=getattr(Module,'randint')# calling the function and storing# the value in resres=func(1,9)# Printing the resultprint(res)

Output:

6

What is exec() method

The exec() function is used for the dynamic execution of Python programs which can either be a string or object code. If it is a string, the string is parsed as a suite of Python statements which is then executed unless a syntax error occurs and if it is an object code, it is simply executed. We must be careful that the return statements may not be used outside of function definitions not even within the context of code passed to the exec() function. It doesn’t return any value, hence returns None.

Syntax of exec() method

Syntax:exec(object[, globals[, locals]])

  • object: As already said this can be a string or object code
  • globals: This can be a dictionary and the parameter is optional
  • locals: This can be a mapping object and is also optional

Return:  None.

Example 1

Using the random function of the random module and calling it using exec() method. The random module generates a decimal number between 0 and 1.

Python3
if__name__=="__main__":# Importing a module randomimportrandom# Using random function of random# module as funcfunc="random.random"# calling the function and storing# the value in resexec(f"x ={func}")res=x()# Printing the resultprint(res)

Output:

0.640045711797753

Example 2

Here also we are generating a decimal number between 0 and 1.

Python3
if__name__=="__main__":# Importing a module randomimportrandom# Using random function of random# module as funcfunc="random"# calling the function and storing# the value in resexec(f"x = random.{func}")res=x()res1=round(res,4)# Printing the resultprint(res1)

Output:

0.6221

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp