فهم Class Methods في بايثون: دليلك الشامل للمبتدئين

مرحباً بك في درس جديد من سلسلة تعلم OOP في بايثون! اليوم سنتعرف على مفهوم مهم جداً وهو Class Methods أو الطرق الخاصة بالكلاس. إذا كنت تتساءل عن الفرق بين الطرق العادية وطرق الكلاس، فأنت في المكان الصحيح!

ما هي Class Methods؟

Class Methods هي دوال (Methods) تنتمي إلى الكلاس نفسه وليس إلى الـ Object (Instance) المنفرد. هذا يعني أنه يمكننا استدعاؤها مباشرة من اسم الكلاس دون الحاجة إلى إنشاء Object منه أولاً!

الميزة الرئيسية: تعمل Class Methods على مستوى الكلاس ككل، وليس على مستوى الـ Objects الفردية.

class Student:
    # This is a class variable
    school_name = "Codex Academy"

    @classmethod
    def get_school_name(cls):
        return cls.school_name

# We can call the method directly from the class
print(Student.get_school_name())  # Output: Codex Academy

في المثال أعلاه، لاحظ أننا استدعينا get_school_name() مباشرة من Student دون إنشاء Object!

كيفية تعريف Class Methods

لتعريف Class Method، نستخدم ديكوراتور @classmethod قبل تعريف الدالة. المعلمة الأولى يجب أن تكون cls (اختصار لـ class) والتي تشير إلى الكلاس نفسه.

class Car:
    wheels = 4  # Common property for all cars

    def __init__(self, brand, color):
        self.brand = brand  # Property specific to each object
        self.color = color

    @classmethod
    def get_wheel_count(cls):
        # cls refers to the Car class itself
        return cls.wheels

# Usage
print(Car.get_wheel_count())  # Output: 4

# We can also call it from the object
my_car = Car("Toyota", "Red")
print(my_car.get_wheel_count())  # Output: also 4

الفرق بين Class Methods و Instance Methods

لنفهم الفرق بشكل أوضح، دعنا نقارن بين النوعين:

النوع ينتمي إلى المعلمة الأولى الاستخدام
Instance Method الـ Object self يعمل على بيانات الـ Object المنفرد
Class Method الكلاس (Class) cls يعمل على بيانات الكلاس المشتركة
class BankAccount:
    # Class variable
    bank_name = "National Bank"
    interest_rate = 0.05

    def __init__(self, owner, balance):
        # Instance variables
        self.owner = owner
        self.balance = balance

    # Instance Method - operates on the object
    def deposit(self, amount):
        self.balance += amount
        return f"Deposited {amount}. New balance: {self.balance}"

    # Class Method - operates on the class
    @classmethod
    def get_bank_info(cls):
        return f"Bank name: {cls.bank_name}, Interest rate: {cls.interest_rate}"

# Using Class Method
print(BankAccount.get_bank_info())  # Works without creating an object

# Using Instance Method
account = BankAccount("Ahmed", 1000)
print(account.deposit(500))  # Works on the specific object

الاستخدام الشائع: المنشئات البديلة (Alternative Constructors)

أحد أكثر استخدامات Class Methods فائدة هو إنشاء منشئات بديلة تسمح لنا بإنشاء Objects بطرق مختلفة.

class Date:
    def __init__(self, day, month, year):
        self.day = day
        self.month = month
        self.year = year

    @classmethod
    def from_string(cls, date_string):
        # Split text into parts: "15-08-2024" → ["15", "08", "2024"]
        day, month, year = date_string.split("-")
        # Return a new object using the primary constructor
        return cls(int(day), int(month), int(year))

    def display(self):
        return f"{self.day}/{self.month}/{self.year}"

# Traditional method
date1 = Date(15, 8, 2024)
print(date1.display())  # Output: 15/8/2024

# Using Class Method as an alternative constructor
date2 = Date.from_string("20-12-2024")
print(date2.display())  # Output: 20/12/2024

متى نستخدم Class Methods؟

  1. عندما تحتاج العمل على بيانات مشتركة بين جميع الـ Objects
  2. لإنشاء منشئات بديلة بطرق مختلفة لإنشاء الـ Objects
  3. عندما تريد تنفيذ عمليات متعلقة بالكلاس وليس بـ Object معين
class Product:
    # Class variable
    tax_rate = 0.15

    def __init__(self, name, price):
        self.name = name
        self.price = price

    @classmethod
    def set_tax_rate(cls, new_rate):
        cls.tax_rate = new_rate
        return f"Tax rate changed to {new_rate}"

    @classmethod
    def calculate_tax(cls, price):
        return price * cls.tax_rate

# Change tax for the whole class
Product.set_tax_rate(0.20)

# Calculate tax for any price
tax = Product.calculate_tax(100)
print(f"Tax on 100 is: {tax}")  # Output: Tax on 100 is: 20.0

الأخطاء الشائعة وتجنبها

خطأ شائع: نسيان استخدام @classmethod أو استخدام self بدلاً من cls

class Example:
    @classmethod
    def correct_method(cls): # Correct
        return "This is correct"

    def wrong_method(self): # Error (this is an instance method)
        return "This is wrong if you want a class method"

# Correct
Example.correct_method()

# Error (will cause an error unless an object is created first)
# Example.wrong_method()  # Will fail!

لماذا cls وليس self؟

عند استدعاء Student.get_school_name() تمرر بايثون الكلاس نفسه كأول Parameter، فيستقبله cls. وعند استدعائه من Object، تمرر الكلاس أيضاً لا الـ Object. هذا يسمح للوراثة بالعمل: cls في الـ Class الابنة يشير إليها، فتعيد قيمتها الخاصة. لو استخدمت self لما استطعت الاستدعاء من الكلاس أصلاً. هذا الفرق بين class methods بايثون و instance methods هو أساس المنشئات البديلة.

خلاصة الدرس

  • Class Methods تنتمي للكلاس وليس للـ Objects المنفردة
  • نعرفها باستخدام @classmethod والمعلمة cls
  • يمكن استدعاؤها مباشرة من اسم الكلاس
  • مفيدة للعمل على البيانات المشتركة وإنشاء منشئات بديلة