לדלג לתוכן

משתנה לוקלי לעומת משתנה גלובלי

  • משתנה לוקלי:
    משתנים לוקלים הם משתנים שמוגדרים בפונקציה או בבלוק קוד. יש להם היקף מקומי (סקופ מקומי), כלומר אפשר לגשת אליהם רק בתוך הפונקציה או הבלוק שבו הם מוגדרים. לאחר שהקוד יוצא מהסקופ איי אפשר לגשת למשתנים (הם נהרסים)
    ```python
    def example_function():
    # Local variable
    local_var = 5
    print("Inside the function:", local_var)

Calling the function

example_function()

Attempting to access the local variable outside the function will result in an error

- **משתנה גלובלי:**
משתנים גלובלים הם משתנים שמוגדרים מחוץ לפונקציות או לבלוק קוד, ויש להם היקף חיצוני (סקופ חיצוני), כלומר אפשר לגשם אליהם מכל חלק בקוד, כולל מפונקציות.
```python
# Global variable
global_var = 10

def example_function():
    # Accessing the global variable
    print("Inside the function:", global_var)

# Calling the function
example_function()

# Accessing the global variable outside the function
print("Outside the function:", global_var)

טרמינולוגיה

  • סימבול - משתנה, פונקציה, כל דבר שמגדירים ובעל שם.
  • אורך חיים של משתנה (variable lifetime) - הסקופ של איזשהו סימבול - מאיפה עד איפה אפשר להשתמש בסימבול כלשהו.

פונקציה מובנית globals

  • מציגה את כל המשתנים הגלובלים בתוכנית
    x = 5
    y = 7
    print(globals())  # Will print all global variables
    
    def func():
        a = 3
        print(globals())  # Will print all global variables
    
    func()
    

פונקציה מובנית locals

  • מציגה את המשתנים הלוקלים של אותו סקופ
    x = 5
    y = 3
    print(locals())  # Will print all variables in the current scope (module level)
    
    def func():
        a = 3
        print(locals())  # Will print all variables in the current scope (function level)
    
    func()
    
  • המשתנים הלוקלים של הסקופ של המודול == משתנים גלובלים, כי אפשר להשתמש במשתנים הלוקלים של המודול בכל המודול - בדיוק כמו משתנים גלובלים.

סינטקס global

  • בתוך פונקציות אפשר לגשת לערכים של משתנים גלובלים אבל איי אפשר לשנות את הערכים, בשביל לשנות את הערכים נשתמש בglobal
    # Global variable
    global_var = 10
    
    def example_function():
        # This creates a local variable with the same name as the global variable
        local_var = 5
        print("Inside the function:")
        print("Local variable:", local_var)
        print("Global variable:", global_var)
    
        # Modifying the local variable
        local_var += 1
    
        # Modifying the global variable using the 'global' keyword
        global global_var 
        global_var += 2
    
        print("After modifications:")
        print("Local variable:", local_var)
        print("Global variable:", global_var)
    
    # Calling the function
    example_function()
    
    # Outside the function, global variable remains unchanged
    print("Outside the function:")
    print("Global variable:", global_var)
    

    אף פעם אל תשתמש בglobal.
    פונקציות לא אמורות לשנות משתנים גלובליים
  • אם לפונקציה יש באג, יהיה קשה למצוא את הבאג
  • כל מה שקורה בפונקציה אמור להישאר בפונקציה, וכשפונקציה משנה משתנה גולבלי היא שוברת את העקרון הזה וזה יכול להוביל לבאגים.

סינטקס nonlocal

  • אז אפשר להשתמש בglobal כדי לשנות משתנה גלובלי מ-scope, מה אם אנחנו רוצים לשנות משתנה שאינו משתנה גלובלי אבל לא ב-scope שלנו?
    def outer_function():
        outer_variable = 10
    
        def inner_function():
            nonlocal outer_variable
            outer_variable += 5
            print("Inner function: modified outer_variable =", outer_variable)
    
        inner_function()
        print("Outer function: outer_variable =", outer_variable)
    
    # Call the outer function
    outer_function()
    
  • הפיצ'ר nonlocal הוא חסר תועלת, לעולם אל תשתמש בו. זה תמיד וצר קוד לא טוב (לא קריא ובאגי) ונדיר ביותר למצוא סיטואציה הגיונית שנצטרך להשתמש בו.