Inheritance & encapsulation · יורשת ואינקספולציה
Build on an existing class
- Inheritance lets a new class reuse an existing one.
- The new class is the subclass (child); the original is the superclass (parent).
- Write
class Bird(Animal):—Birdgets all ofAnimal's methods. (In exam pseudocode:CLASS Bird INHERITS Animal.)
בנה על מחלקה קיימת
- ירישה מאפשרת לקלאס חדש להשתמש בקלאס קיים.
- הקלאס החדש הוא קלאס בן (ילד); הקלאס המקורי הוא קלאס אב (הורה).
- כתוב
class Bird(Animal):—Birdיקבל את כל הפונקציות שלAnimal. (בסימולית לבחינות:CLASS Bird INHERITS Animal.)
Call the parent with super()
- A subclass can add its own attributes in
__init__. - Use
super().__init__(...)to run the parent's__init__first. - This avoids repeating the parent's setup code.
קריאה לאב באמצעות super()
- קלאס בן יכול להוסיף תכונות משלו ב
__init__. - השתמש ב
super().__init__(...)כדי לרץ תחילה את ה__init__של האב. - הדבר נמנע מהכפלת קוד ההגדרה של האב.
class Animal:
def __init__(self, name):
self.name = name
def describe(self):
return self.name + " is an animal"
class Bird(Animal):
def fly(self):
return self.name + " flies"
b = Bird("Robin")
print(b.describe()) # inherited from Animal
print(b.fly()) # new in Bird
Override a method
- A subclass can override a method: define one with the same name.
- The subclass's version is used instead of the parent's.
- This lets each class behave in its own way.
החלפת פונקציה
- קלאס בן יכול להחליף פונקציה: להגדיר אחת בשם זהה.
- הגרסה של קלאס הבן תשימש במקום גרסת האב.
- הדבר מאפשר לכל קלאס להתנהג בצורה הייחודית שלו.
class Animal:
def speak(self):
return "..."
class Cow(Animal):
def speak(self):
return "Moo"
print(Cow().speak())
Encapsulation
- Encapsulation means keeping an object's data safe inside it.
- Python has no real "private", but a leading underscore (
self._balance) signals "do not touch from outside". - Other code should use methods to read or change the data, not reach in directly.
עטיפה
- עטיפה פירושה שמירת נתוני האובייקט בבטחון בתוך עצמו.
- לפייתון אין "פרטי" אמיתי, אך קו תחתון בהתחלה (
self._balance) מסמן "אל תגיע ממחוצה". - קוד אחר צריך להשתמש בפונקציות לקריאה או שינוי הנתונים, ולא לגעת ישירות.
Polymorphism
- Polymorphism means one method name, but different behaviour per class.
- A loop can call
.speak()on many objects without knowing their exact type. - Each object responds in its own way.
רב-צורה
- רב-צורה פירושה שם פונקציה אחד, אך התנהגות שונה לכל קלאס.
- מחזור יכול לקרוא ל
.speak()על מספר אובייקטים מבלי לדעת את סוגם המדויק. - כל אובייקט מגיב בצורה הייחודית שלו.
class Duck:
def speak(self):
return "Quack"
class Cow:
def speak(self):
return "Moo"
for animal in [Duck(), Cow()]:
print(animal.speak())
Common mistakes
- A subclass inherits from its parent and can add or override methods.
- Keep data private and reach it through methods (encapsulation).
טעויות נפוצות
- מחלקה נגזרת יורשת מההורה שלה ויכולה להוסיף או להחליף שיטות.
- שמר על נתונים כפרטיים והתחבר אליהם דרך שיטות (אקספונציה).
Now you try
- Use inheritance, overriding, encapsulation, and calling methods on different objects.
- Press Check answer to test your code.
כעת תנסו בעצמכם
- השתמש בירישה, החלפה, אקספונציה ובקריאה לשיטות על אובייקטים שונים.
- לחץ על בדוק תשובה כדי לבדוק את הקוד שלך.
The class Animal is given. Write a subclass Cat(Animal) that inherits from it and adds a method speak(self) returning "Meow". (It should still have the inherited name_is.) · הכיתה Animal נתונה. כתוב תת-כיתה (subclass) Cat(Animal) שיורשת ממנה ומוסיפה שיטה speak(self) החזרתי "Meow". (היא אמורה לשמור על ה-name_is המיורש).
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
The class Shape is given (its area returns 0). Write Square(Shape): its __init__(self, side) should call super().__init__("square"), store side, and override area to return side * side. · הכיתה Shape נתונה (ה-area שלה מחזירה 0). כתוב Square(Shape): ה-__init__(self, side) שלה צריך לקרוא ל-super().__init__("square"), לאחסן את side, וללעבור על (override) את ה-area כדי להחזיר side * side.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Classes Dog and Cat are given, each with a speak(). Write speak_all(animals) that returns a list of each animal's speak() result, in order. · הכיתות Dog ו-Cat נתונות, כל אחת עם ⟨speak()⟩. כתוב speak_all(animals) שחזר רשימה של תוצאת ה-speak() של כל בעל-חיים, בסדר.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.
Write a class Account whose __init__(self) sets a private balance self._balance to 0. Add deposit(self, amount) to add to it, and balance(self) to return it. Other code should use these methods, not touch _balance directly. · כתוב כיתה Account שבה ה-__init__(self) מגדיר אופני מאוזן (balance) פרטי self._balance ל-0. הוסף ⟨deposit(self, amount)⟩ להוסיף אליו, ו-balance(self) שחזר אותו. קוד אחר צריך להשתמש בשיטות אלו ולא לגעת ב-_balance ישירות.
Click Run to see the output here. · לחץ על הרץ כדי לראות את התוצא כאן.