Menu
Coddy logo textTech
flag Ar iconالعربيةdown icon

إعادة تعريف الدوال (Method Overriding)

جزء من قسم Object Oriented Programming في رحلة Python على Coddy — الدرس 19 من 64.

يسمح تجاوز الطريقة (Method overriding) للفئة الابنة بتقديم تنفيذ خاص بها لطريقة موجودة بالفعل في الفئة الأب.

إليك مثال على فئة أساسية (parent class) تحتوي على دوال (methods):

class Animal:
    def __init__(self, name):
        self.name = name
    
    def make_sound(self):
        print("Some generic animal sound")
    
    def info(self):
        print(f"I am {self.name}")

أنشئ فئة تابعة تقوم بتجاوز دالة واحدة:

class Dog(Animal):
    def make_sound(self):
        print("Woof! Woof!")  # تجاوز دالة الفئة الأب

تستبدل الطريقة make_sound في Dog تلك الموجودة في Animal، ولكن info لا تزال موروثة دون تغيير.

قم بإنشاء مثيلات واختبار الأساليب:

animal = Animal("Generic Animal")
dog = Dog("Buddy")

استدعاء الطريقة التي تم تجاوزها:

animal.make_sound()
dog.make_sound()

استدعاء الطريقة (method) غير المُتجاوزة:

animal.info()
dog.info()

الناتج:

Some generic animal sound
Woof! Woof!
I am Generic Animal
I am Buddy

يمكنك تجاوز أي دالة موروثة:

class Cat(Animal):
    def make_sound(self):
        print("Meow!")
    
    def info(self):
        print(f"I am {self.name}, a sneaky cat")

cat = Cat("Whiskers")
cat.make_sound()
cat.info()

المخرجات:

Meow!
I am Whiskers, a sneaky cat

نقطة رئيسية: تتيح خاصية تجاوز الدوال (Method overriding) للفئات الفرعية تخصيص السلوك الموروث. ما عليك سوى تعريف دالة بنفس الاسم في الفئة الفرعية، حيث سيتم استخدام نسخة الفئة الفرعية بدلاً من نسخة الفئة الأب.

challenge icon

التحدي

متوسط

في هذا التحدي، ستقوم بتنفيذ تسلسل هرمي للأشكال.

  • shape.py - يحتوي على فئة Shape الأساسية مع سمة color والأساليب (methods)
  • circle.py - يحتوي على فئة Circle التي ترث من Shape
  • square.py - يحتوي على فئة Square التي ترث من Shape

يحتوي كل ملف على تعليقات TODO مفصلة سترشدك خطوة بخطوة خلال عملية التنفيذ.

ورقة مرجعية

يسمح تجاوز الدوال (Method overriding) للفئة الابنة (child class) بتقديم تنفيذ خاص بها لدالة موجودة بالفعل في الفئة الأب (parent class).

مثال على الفئة الأب:

class Animal:
    def __init__(self, name):
        self.name = name
    
    def make_sound(self):
        print("Some generic animal sound")
    
    def info(self):
        print(f"I am {self.name}")

فئة ابنة تتجاوز دالة:

class Dog(Animal):
    def make_sound(self):
        print("Woof! Word!")  # تجاوز دالة الأب

تقوم الدالة make_sound في Dog باستبدال الدالة الموجودة في Animal، ولكن تظل info موروثة دون تغيير.

يمكنك تجاوز دوال متعددة:

class Cat(Animal):
    def make_sound(self):
        print("Meow!")
    
    def info(self):
        print(f"I am {self.name}, a sneaky cat")

نقطة رئيسية: ببساطة قم بتعريف دالة بنفس الاسم في الفئة الابنة. سيتم استخدام نسخة الابنة بدلاً من نسخة الأب.

جرّب بنفسك

from shape import Shape
from circle import Circle
from square import Square

# معالج حالات الاختبار
test_case = input()

if test_case == "base_shape":
    # اختبار فئة الشكل الأساسية (Shape)
    shape = Shape("green")
    print(f"Color: {shape.color}")
    print(f"Area: {shape.area()}")
    print("Describe output:")
    shape.describe()

elif test_case == "circle_basics":
    # اختبار إنشاء الدائرة والأساليب الأساسية
    circle = Circle("red", 5)
    print(f"Color: {circle.color}")
    print(f"Radius: {circle.radius}")
    print(f"Area (rounded): {round(circle.area(), 2)}")
    print("Describe output:")
    circle.describe()

elif test_case == "square_basics":
    # اختبار إنشاء المربع والأساليب الأساسية
    square = Square("blue", 4)
    print(f"Color: {square.color}")
    print(f"Side length: {square.side_length}")
    print(f"Area: {square.area()}")
    print("Describe output:")
    square.describe()

elif test_case == "various_sizes":
    # اختبار عدة نماذج بأبعاد مختلفة
    shapes = [
        Circle("yellow", 2),
        Circle("orange", 7.5),
        Square("purple", 3),
        Square("black", 10)
    ]
    
    for i, shape in enumerate(shapes, 1):
        print(f"Shape {i}:")
        shape.describe()
        print(f"Area: {round(shape.area(), 2)}")
        print()  # سطر فارغ لسهولة القراءة

elif test_case == "shape_polymorphism":
    # اختبار سلوك تعدد الأشكال مع قائمة من الأشكال
    shapes = [
        Shape("white"),
        Circle("red", 3),
        Square("blue", 4)
    ]
    
    print("Polymorphic behavior demonstration:")
    for shape in shapes:
        shape.describe()
        print(f"Area: {round(shape.area(shape_polymorphism), 2)}")
        print()  # سطر فارغ لسهولة القراءة

elif test_case == "original_test_case":
    # تشغيل كود الاختبار الأصلي من التحدي
    circle = Circle("red", 5)
    square = Square("blue", 4)

    # اختبار أسلوب الوصف (describe)
    circle.describe()
    square.describe()

    # اختبار أسلوب المساحة (area)
    print(f"Circle area: {circle.area()}")
    print(f"Square area: {square.area()}")
quiz iconاختبر نفسك

يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.

جميع دروس Object Oriented Programming