Commit 538fa786 by Patryk Czarnik

dziedziczenie - override

parent 640c3c42
...@@ -8,7 +8,7 @@ class Osoba: ...@@ -8,7 +8,7 @@ class Osoba:
return f'{self.imie} {self.nazwisko} ({self.wiek} lat)' return f'{self.imie} {self.nazwisko} ({self.wiek} lat)'
def przedstaw_sie(self): def przedstaw_sie(self):
print(f'Nazywam się {self.imie} {self.nazwisko} i mam {self.wiek} lat') print(f'Nazywam się {self.imie} {self.nazwisko} i mam {self.wiek} lat.')
def jest_pelnoletnia(self): def jest_pelnoletnia(self):
return self.wiek >= 18 return self.wiek >= 18
...@@ -20,9 +20,25 @@ class Student(Osoba): ...@@ -20,9 +20,25 @@ class Student(Osoba):
super().__init__(imie, nazwisko, wiek) super().__init__(imie, nazwisko, wiek)
self.rok = rok self.rok = rok
self.kierunek = kierunek self.kierunek = kierunek
self.oceny = []
# Klasa podrzędna może:
# a) niczego nie zmieniać w odziedziczonej metodzie - np. nie zmieniamy "jest_pelnoletnia"
# b) dodać nowe metody - obsługa ocen
def dodaj_ocene(self, ocena):
self.oceny.append(ocena)
def srednia_ocen(self): def srednia_ocen(self):
return 4.5 import statistics
if not self.oceny:
return None
return statistics.mean(self.oceny)
# c) nadpisać (override) metodę, czyli zmienić jej implementację na inną
def przedstaw_sie(self):
# możliwe jest: super().przedstaw_sie()
print(f'Hej, tu {self.imie} {self.nazwisko}, studiuję {self.kierunek}.')
class Sklep: class Sklep:
...@@ -58,8 +74,14 @@ print('dane studenta:', student.imie, student.nazwisko, student.kierunek) ...@@ -58,8 +74,14 @@ print('dane studenta:', student.imie, student.nazwisko, student.kierunek)
# Tylko obiekty klasy Student posiadają dodatkową metodę srednia_ocen # Tylko obiekty klasy Student posiadają dodatkową metodę srednia_ocen
#ERR print('średnia ocen osoby:', osoba.srednia_ocen()) #ERR print('średnia ocen osoby:', osoba.srednia_ocen())
student.dodaj_ocene(5)
student.dodaj_ocene(4)
student.dodaj_ocene(4)
print('średnia ocen studenta:', student.srednia_ocen()) print('średnia ocen studenta:', student.srednia_ocen())
print() print()
osoba.przedstaw_sie() osoba.przedstaw_sie()
student.przedstaw_sie() student.przedstaw_sie()
print('Przedstawimy studenta w taki sposób, jak przedstawia się osoba:')
Osoba.przedstaw_sie(student)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment