![]() |
VOOZH | about |
In Python, function variables have local scope and 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.
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.
42
Explanation: get_variable() defines a local variable var with the value 42 and returns it. Since local variables cannot be accessed outside their function, the returned value is assigned to res.
Table of Content
A closure 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.
42
Explanation: outer_fun() defines a local variable var and returns inner_fun(), which accesses var. Assigned to get_var, inner_fun() retains access to var even after outer_fun() executes, demonstrating a closure.
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.
15
Explanation: modify(var) adds 10 to var and returns it. original_var (5) is passed to modify(), returning 15, which is stored in res.
By storing a variable as an instance attribute of a class, 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.
42
Explanation: VariableHolder class has an __init__ method that initializes the instance variable var with 42. An instance holder is created and holder.var is accessed to print 42.