Dziedziczenie wielopoziomowe
Masz już za sobą dziedziczenie pojedyncze i wielokrotne. W tym ćwiczeniu zaimplementujesz dziedziczenie wielopoziomowe, tworząc nową wersję klasy Smartphone.
Na dobry początek poniżej zdefiniowano klasy Computer i Tablet. Warto zwrócić uwagę, że Tablet dziedziczy po klasie Computer. Powodzenia!
class Computer:
def __init__(self, brand):
self.brand = brand
def browse_internet(self):
print(f"Using {self.brand}'s default internet browser.")
class Tablet(Computer):
def __init__(self, brand, apps):
Computer.__init__(self, brand)
self.apps = apps
def uninstall_app(self, app):
if app in self.apps:
self.apps.remove(app)
To ćwiczenie jest częścią kursu
Programowanie obiektowe w Pythonie – poziom średnio zaawansowany
Instrukcje do ćwiczenia
- Zdefiniuj klasę
Smartphone, która dziedziczy po klasieTablet, wywołaj konstruktor klasy nadrzędnej i zdefiniuj atrybut instancjiphone_number. - Utwórz metodę
send_text, która wysyła wiadomość tekstowąmessagedo odbiorcyrecipient, korzystając z numeru telefonuSmartphone. - Utwórz instancję klasy
Smartphoneo nazwiepersonal_phone, wywołaj na niej metodę.browse_internet(), odinstaluj aplikacjęWeatheri wyślij do Chucka wiadomość tekstową o treściTime for a new mission!.
Interaktywne ćwiczenie praktyczne
Spróbuj tego ćwiczenia, uzupełniając ten przykładowy kod.
# Create a Smartphone class that inherits from Tablet
class ____(____):
def __init__(self, brand, apps, phone_number):
____.____(self, ____, ____)
self.phone_number = ____
# Create send_text to send a message to a recipient
def ____(self, message, recipient):
print(f"Sending {____} to {____} from {____.____}")
# Create an instance of Smartphone, call methods in each class
____ = Smartphone("Macrosung", ["Weather", "Camera"], "801-932-7629")
personal_phone.____()
personal_phone.____("____")
personal_phone.____("____", "Chuck")