דריסת מתודות
חלק מהיחידה תכנות מונחה עצמים במסלול ה-Python של Coddy. שיעור 19 מתוך 64.
דריסת מתודה מאפשרת למחלקת ילד לספק מימוש משלה למתודה שכבר קיימת במחלקת האב.
הנה דוגמה למחלקת אב עם מתודות:
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()קראו למתודה שלא נדרסה:
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נקודה מרכזית: דריסת מתודות מאפשרת למחלקות צאצא להתאים אישית התנהגות שעברה בירושה. פשוט מגדירים מתודה בעלת אותו שם במחלקת הצאצא. הגרסה של הצאצא תשמש במקום הגרסה של ההורה.
אתגר
בינוניבאתגר הזה תממשו היררכיית צורות.
shape.py- מכיל את מחלקת האבShapeעם המאפייןcolorומתודותcircle.py- מכיל את המחלקהCircleשיורשת מ-Shapesquare.py- מכיל את המחלקהSquareשיורשת מ-Shape
כל קובץ מכיל הערות מפורטות של TODO שינחו אתכם שלב אחר שלב בתהליך המימוש.
נסו בעצמכם
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 = 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 = 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()}")השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.
כל השיעורים ביחידה תכנות מונחה עצמים
1יסודות התכנות מונחה העצמים (OOP)
קבצים חיצונייםמבוא ל-OOPמחלקות לעומת אובייקטיםהפרמטר selfמתודותמאפייניםשיטת הבנאי (__init__)חזרה: מחשבון פשוט5פולימורפיזם
בחינה מחדש של דריסת מתודותטיפוסיות ברווזמחלקות ומתודות אבסטרקטיותעיצוב ממשקיםסיכום – מחשבון צורות8מושגים מתקדמים בתכנות מונחה עצמים
קומפוזיציה לעומת הורשהMixinsמתודות סטטיות ומתודות מחלקהדקורטורים למחלקותמנהלי הקשרתרגלו בעצמכם: קומפיילר Python אונליין