استيراد * في بايثون

0
في هذه التدوينة سنتحدث عن
from module import *



وكيفية عملها ولماذا يجب ان لا نستخدم هذه الطريقة في عملية الاستراد .



استراد * من module
هذا السطر يعني اني اريد الوصول الى جميع الأسماء الموجودة داخل module ومن المفترض اني استطيع استعمال جميع الوظائف والصفوف الموجودة داخل هذا الموديل .

ومن أجل فهم اكبر سنقوم باخذ مثال بانشاء ملف something.py

# something.py

public_variable = 42
_private_variable = 141

def public_function():
    print("I'm a public function! yay!")

def _private_function():
    print("Ain't nobody accessing me from another module...usually")

class PublicClass(object):
    pass

class _WeirdClass(object):
    pass
الان نقوم بتشغيل مترجم بايثونIDLE ونقوم بتشغيل السطر التالي :

from something import *
الان نقوم بتجريب السطور التالية
from something import *
public_variable
42
_private_variable
...
NameError: name '_private_variable' is not defined
public_function()
"I'm a public function! yay!"
_private_function()
...
NameError: name '_private_function' is not defined
c = PublicClass()
c

c = _WeirdClass()
...
NameError: name '_WeirdClass' is not defined
اذاالسطر from something import * قام باستراد جميع الأسماء الموجودة داخل ملف something ماعدا الأسماء التي تبدا ب _ لانها تعني أسماء خاصة .
اذا ما هو الحل؟
لم نقم بذكر بعد __all__ وماذا تعني .
__all__ هي قائمة تحتوي على سلاسل لتحديد وتعريف الرموز الموجودة في module ويتم استخدامها عند عملية استراد *.
عندما لا نقوم بتعريف __all__ فان عملية استراد * ستقوم باستراد جميع الأسماء ما عدا الاسماء التي تبدا بالعلامة _ والتي تعني انها أسماء خاصة .
الان سنقوم بتعريف __all__ في ملف something.py .

# something.py

__all__ = ['_private_variable', 'PublicClass']

# The rest is the same as before

public_variable = 42
_private_variable = 141

def public_function():
    print("I'm a public function! yay!")

def _private_function():
    print("Ain't nobody accessing me from another module...usually")

class PublicClass(object):
    pass

class _WeirdClass(object):
    pass
الان من المفروض عند كتابةالسطر from something import * ان يقوم باستراد كل من _private_variables و PublicClass
>>> from something import *
>>> public_variable
...
NameError: name 'public_variable' is not defined
>>> _private_variable
0
>>> public_function()
...
NameError: name 'public_function' is not defined
>>> _private_function()
...
NameError: name '_private_function' is not defined
>>> c = PublicClass()
>>> c

>>> c = _WeirdClass()
...
NameError: name '_WeirdClass' is not defined
كان هذاهو درسنا اليوم أرجوا أن تكونوا قد استمتعتم واستفدتم وأي تعليق عن الموضوع مرحبا به

لا يوجد تعليقات

أضف تعليق