Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python Function Parameters and Arguments
Next article icon

In Python, function variables havelocal scopeand cannot be accessed directly from outside. However, their values can still be retrieved indirectly.For example, if a function defines var = 42, it remains inaccessible externally unless retrieved indirectly.

Returning the Variable

The most efficient way to access a function variable outside its scope is by returning it. The function retains its local scope and the variable remains encapsulated.

Python
defget_variable():var=42returnvar# accessing the function variable outside the functionres=get_variable()print(res)

Output
42

Explanation: get_variable() defines a local variablevar with the value 42 and returns it. Since local variables cannot be accessed outside their function, the returned value is assigned tores.

Using a closure

Aclosure allows a nested function to remember and access variables from its enclosing function even after execution. This method ensures encapsulation while avoiding global scope pollution. Closures are useful for maintaining state and are often used in callbacks and decorators.

Python
defouter_fun():var=42definner_fun():returnvarreturninner_fun# create a closureget_var=outer_fun()# accessing the function variable outside the functionprint(get_var())

Output
42

Explanation: outer_fun() defines a local variable var and returns inner_fun(), which accessesvar. Assigned toget_var,inner_fun()retains access tovar even afterouter_fun() executes, demonstrating a closure.

Using function parameters

Instead of directly accessing a variable, passing it as a function parameter allows modifications without breaking encapsulation. This method follows functional programming principles, making the code modular and reusable. It is efficient and ensures no unintended side effects.

Python
defmodify(var):var+=10returnvar# Define a variable outside the functionoriginal_var=5# Passing the variable to the functionres=modify(original_var)print(res)

Output
15

Explanation: modify(var) adds 10 to var and returns it. original_var (5) is passed tomodify(), returning 15, which is stored inres.

Using class

By storing a variable as an instance attribute of aclass, it can be accessed outside the function scope without modifying Python’s variable scope rules. This method is useful when multiple related variables need to be grouped, but it comes with slight overhead due to object creation.

Python
classVariableHolder:def__init__(self):self.var=42# creating an instance of the classholder=VariableHolder()# accessing the variable through the instanceprint(holder.var)

Output
42

Explanation: VariableHolder class has an__init__ methodthat initializes the instance variable var with 42. An instance holder is created andholder.varis accessed to print 42.


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