الدرس 3 من 8
الـ Modules والـ Packages
مفيش مشروع حقيقي مكتوب في ملف واحد.
الـ Module = ملف بايثون
أي ملف .py اسمه module. تقدر تكتب functions وكلاسات في ملف، وتستخدمها من ملف تاني بـ import. زي ما المطبخ ليه درج للسكاكين ودرج للمعالق، مش كله مرمي في درج واحد.
# pricing.py -> a module with helper functions VAT = 0.14 def add_vat(price): return round(price * (1 + VAT), 2) def apply_discount(price, percent): return round(price * (1 - percent / 100), 2)
# main.py -> uses the pricing module import pricing # import the whole module from pricing import apply_discount # import one function directly price = 1000 print(pricing.add_vat(price)) print(apply_discount(price, 20)) print(pricing.VAT)
| الطريقة | بتستخدمها إزاي |
|---|---|
import pricing | pricing.add_vat() واضحة ومعروف الدالة جاية منين |
from pricing import add_vat | add_vat() على طول، أقصر |
import numpy as np | np.array() اسم مختصر، ده العرف في مكتبات الـ AI |
from pricing import * | بلاش، بتجيب كل حاجة وممكن الأسماء تتلخبط |
المكتبة القياسية: حاجات جاهزة ببلاش
بايثون جاية ومعاها مكتبات كتير متسطبة، اسمها Standard Library. قبل ما تكتب حاجة من الصفر، دوّر يمكن تكون موجودة.
import random from datetime import date, timedelta import math # Pick a random winner for a giveaway winners = ["Ali", "Sara", "Omar", "Laila"] print("Winner:", random.choice(winners)) # Delivery date = today + 3 days delivery = date(2026, 9, 22) + timedelta(days=3) print("Delivery on:", delivery) print(math.sqrt(144))
السطر اللي في كل مشروع: __main__
هتشوف السطر ده في كل مشروع تقريباً. معناه: «الكود اللي تحتي يتنفذ بس لو الملف ده اتشغل مباشرة، مش لو حد عمله import». كده تقدر تحط تجارب في الملف من غير ما تتنفذ لما ملف تاني يستورده.
def add_vat(price): return round(price * 1.14, 2) if __name__ == "__main__": # Runs only with: python pricing.py # Does NOT run when another file does: import pricing print("Testing:", add_vat(100))
الـ Package = فولدر فيه modules
shop/
main.py
store/ # this folder is a package
__init__.py # marks the folder as a package (can be empty)
products.py
orders.py
# inside main.py:
from store.products import Product
from store.orders import create_order🤖 في الـ AI
from sklearn.model_selection import train_test_split: هنا sklearn package، و model_selection module جواه، و train_test_split function. أول ما تفهم الشكل ده، أي import هتقراه هتفهمه.