0Pricing
Python For Kids · درس

التغليف

استكشف مفاهيم OOP المتقدمة.

التغليف درس مجاني في Python For Kids على CoddyKit. هذا هو الدرس 4 من أصل 5. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Python For Kids، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Python For Kids 5 دروس في المجموع.

التغليف

مرحبًا بكم مجددًا في درس البرمجة كائنية التوجه (OOP)! سنتعلم اليوم التغليف في Python، وهو مفهوم أساسي يساعد على حماية البيانات والأساليب داخل الأصناف.

التغليف — رسم توضيحي 1

ما التغليف؟

التغليف هو مفهوم تجميع البيانات (السمات) والأساليب (الدوال) التي تعمل على تلك البيانات داخل وحدة واحدة تُعرف باسم الصنف. كما يقيّد الوصول المباشر إلى بعض مكونات الكائن، مما يعني إخفاء التمثيل الداخلي للكائن عن العالم الخارجي.

  • إخفاء البيانات: حماية الحالة الداخلية للكائن من التدخل غير المقصود.
  • التحكم في الوصول: تحديد كيفية الوصول إلى البيانات والأساليب أو تعديلها.

يضمن التغليف تحكم الكائنات في بياناتها، ولا يكشف إلا ما هو ضروري.

محددات الوصول

يُطبَّق التغليف في Python باستخدام محددات الوصول للتحكم في مستوى ظهور أعضاء الصنف (السمات والأساليب). توجد ثلاثة أنواع من محددات الوصول:

  • عام: يمكن الوصول إليه من أي مكان.
  • محمي: يمكن الوصول إليه من داخل الصنف وأصنافه الابنة.
  • خاص: لا يمكن الوصول إليه إلا من داخل الصنف نفسه.

لنرَ كيفية استخدام محددات الوصول هذه في Python.

السمات والأساليب العامة

يمكن الوصول إلى الأعضاء العامة من خارج الصنف. وتكون جميع السمات والأساليب عامة افتراضيًا ما لم يُحدَّد خلاف ذلك.

مثال:

# Defines the Person class with public attributes and methods
class Person:
    def __init__(self, name, age):
        self.name = name  # Public attribute
        self.age = age    # Public attribute

    def greet(self):
        print("Hello, my name is " + self.name + "!")  # Public method

# Creates an object of the Person class
person1 = Person("Alice", 30)

# Accesses public attributes and methods
print(person1.name)  # Output: Alice
person1.greet()      # Output: Hello, my name is Alice!

السمات والأساليب المحمية

يُشار إلى الأعضاء المحمية ببادئة تتكون من شرطة سفلية واحدة (_). ويمكن الوصول إليها من داخل الصنف وأصنافه الابنة، لكن لا ينبغي الوصول إليها مباشرةً من خارج الصنف.

مثال:

# Defines the Employee class with protected attributes and methods
class Employee:
    def __init__(self, name, salary):
        self._name = name      # Protected attribute
        self._salary = salary  # Protected attribute

    def _increase_salary(self, amount):
        self._salary += amount  # Protected method
        print(self._name + "'s new salary is " + str(self._salary))

# Creates an object of the Employee class
employee1 = Employee("Bob", 50000)

# Accesses protected attributes and methods (not recommended)
print(employee1._name)  # Output: Bob
employee1._increase_salary(5000)  # Output: Bob's new salary is 55000

السمات والأساليب الخاصة

يُشار إلى الأعضاء الخاصة ببادئة تتكون من شرطتين سفليتين (__). ولا يمكن الوصول إليها إلا من داخل الصنف نفسه، ولا يمكن الوصول إليها مباشرةً من خارج الصنف.

مثال:

# Defines the BankAccount class with private attributes and methods
class BankAccount:
    def __init__(self, owner, balance):
        self.__owner = owner    # Private attribute
        self.__balance = balance  # Private attribute

    def deposit(self, amount):
        self.__balance += amount  # Modifies private attribute
        print("Deposited:", amount)
        self.__show_balance()

    def __show_balance(self):
        print("Current Balance:", self.__balance)  # Private method

# Creates an object of the BankAccount class
account1 = BankAccount("Charlie", 1000)

# Attempts to access private attributes and methods (will cause errors)
# print(account1.__owner)        # AttributeError
# account1.__show_balance()      # AttributeError

# Uses public methods to interact with private attributes
account1.deposit(500)  # Output:
                        # Deposited: 500
                        # Current Balance: 1500

لماذا نستخدم التغليف؟

يوفر التغليف عدة فوائد:

  • التحكم: التحكم في كيفية الوصول إلى البيانات أو تعديلها.
  • الأمان: حماية الحالة الداخلية للكائن من التغييرات غير المقصودة.
  • سهولة الصيانة: جعل الشفرة أسهل في الصيانة وأقل عرضة للأخطاء.

يساعد التغليف على بناء تطبيقات قوية وآمنة.

مثال على التغليف: الفئة Car

لننشئ فئة Car تستخدم التغليف لحماية سماتها وأساليبها.

الشفرة:

# Defines the Car class with encapsulated attributes and methods
class Car:
    def __init__(self, make, model, year):
        self.make = make          # Public attribute
        self.model = model        # Public attribute
        self.__year = year        # Private attribute

    def get_year(self):
        return self.__year  # Public method to access private attribute

    def set_year(self, year):
        if year > 0:
            self.__year = year  # Public method to modify private attribute
            print("Year updated to", self.__year)
        else:
            print("Invalid year!")

    def __display_info(self):
        print(self.make, self.model, self.__year)  # Private method

    def show_info(self):
        self.__display_info()  # Public method that calls a private method

# Creates an object of the Car class
car1 = Car("Tesla", "Model S", 2020)

# Accesses public attributes and methods
print(car1.make)        # Output: Tesla
print(car1.get_year())  # Output: 2020

# Modifies the private attribute using a public method
car1.set_year(2021)     # Output: Year updated to 2021

# Calls a public method that interacts with a private method
car1.show_info()        # Output: Tesla Model S 2021

# Attempts to access private attributes and methods directly (will cause errors)
# print(car1.__year)         # AttributeError
# car1.__display_info()      # AttributeError
# Defines the Student class with encapsulated attributes
class Student:
    def __init__(self, name, grade):
        self.name = name      # Public attribute
        self.__grade = grade  # Private attribute

    def get_grade(self):
        return self.__grade  # Public method to access private attribute

    def set_grade(self, grade):
        if 0 <= grade <= 100:
            self.__grade = grade  # Updates the grade
        else:
            print("Invalid grade!")

# Creates an object of the Student class
student1 = Student("Diana", 85)

# Accesses and modifies the grade using public methods
print(student1.get_grade())  # Output: 85
student1.set_grade(90)
print(student1.get_grade())  # Output: 90

# Attempts to access the private attribute directly (will cause an error)
# print(student1.__grade)     # AttributeError

أحسنتم!

لقد تعلمتم كيفية استخدام التغليف في Python لحماية بياناتكم وأساليبكم داخل الفئات. يساعدكم التغليف على التحكم في الوصول إلى بيانات الكائن، مما يجعل برامجكم أكثر أمانًا وأسهل في الصيانة. واصلوا التدريب من خلال تصميم فئات باستخدام محددات الوصول المناسبة لتعزيز مهاراتكم البرمجية!

التغليف — رسم توضيحي 10

الأسئلة الشائعة

هل درس «التغليف» مجاني؟

نعم — نص درس «التغليف» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Python For Kids، انتقل إلى CoddyKit PRO. تتضمن دورة Python For Kids 5 دروس في المجموع.

ماذا ستتعلم في «التغليف»؟

استكشف مفاهيم OOP المتقدمة. تتمرن على Python For Kids مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ Python For Kids؟

لا تُشترط خبرة سابقة. Python For Kids على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 4 من أصل 5.

كم من الوقت يستغرق درس «التغليف»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس Python For Kids هذا؟

نعم. كل درس في Python For Kids يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. مقدمة إلى OOP
  2. إنشاء الفئات والكائنات
  3. الوراثة
  4. التغليف
  5. تعدد الأشكال
← العودة إلى Python For Kids