...

/

نطاق الوظيفة

نطاق الوظيفة

تعرف على نطاق متغير والمتغيرات العالمية وما يحدث عندما نمرر المتغيرات القابلة للتغيير وغير القابلة للتغيير كمعلمات للوظيفة.

سنغطي ما يلي...

The scope of a function means the extent to which the variables and other data items made inside the function are accessible in code. In Python, the function scope is the function’s body. Whenever a function runs, the program moves into its scope. Once the function has ended, it moves back to the outer scope.

Data lifecycle

In Python, data created inside the function cannot be used from the outside unless it is being returned from the function. Variables in a function are isolated from the rest of the program. When the function ends, they are released from memory and cannot be recovered.

The following code will never work:

Press + to interact
def func():
name = "Stark"
func()
print(name) # Accessing 'name' outside the function

كما نرى، متغير name غير موجود في النطاق الخارجي. وبالمثل، لا تستطيع الدالة الوصول إلى البيانات خارج نطاقها إلا إذا تم تمريرها كمعامل أو كانت ضمن النطاق العام.

Press + to interact
name = "Ned"
def func():
name = "Stark"
func()
print(name) # The value of 'name' remains unchanged.

النطاق العالمي

يشير النطاق العالمي إلى منطقة البرنامج التي توجد فيها متغيرات مُعرّفة خارج جميع الدوال. يمكن الوصول إلى هذه المتغيرات من أي جزء من البرنامج، بما في ذلك الدوال الداخلية، مما يجعلها متاحة عالميًا. يُعد النطاق العالمي النطاق الأعلى في برامج Python ، وتُعرف المتغيرات المُعرّفة فيه بالمتغيرات العالمية.

وفيما يلي بعض النقاط مفتاح حول النطاق العالمي:

    ...