ООП (Об'єктно-орієнтоване програмування)
На цьому уроці розберемо основи об'єктно-орієнтованого програмування в Python: що таке класи, об'єкти, атрибути та методи. Також розглянемо основні принципи ООП та як їх застосовувати на практиці.
Code and results
Published version after Merge. Results were saved by the author; code does not run on this page.
Python · 1
class StudyTracker:
def __init__(self, student_name):
self.student_name = student_name
self.lessons = {}
def add_lesson(self, title):
if title in self.lessons:
raise ValueError
self.lessons[title] = False
#raise NotImplementedError
def complete_lesson(self, title):
if title in self.lessons:
assert (self.lessons[title] != True), "Lesson already finished"
self.lessons[title] = True
else:
raise KeyError(f"Lesson '{title}' not found")
#raise NotImplementedError
#progress() повертає словник {"completed": кількість завершених, "total": кількість усіх, "percent": відсоток від 0 до 100}. Для порожнього трекера percent=0.
def progress(self):
total = len(self.lessons)
completed = sum(self.lessons.values())
percent = 0 if total==0 else completed/total*100
print(f"{self.student_name} - completed: {completed}, total: {total}, percent: {percent}")
#pending_lessons() повертає новий список незавершених назв у порядку додавання.
def pending_lessons(self):
assert (len(self.lessons)), "Study tracker is empty"
pending = []
for title in self.lessons:
if self.lessons[title] == False:
pending.append(title)
print(f"Lessons still pending: {pending}")
return pending
#raise NotImplementedError
# Додай приклади для двох незалежних трекерів та assert-перевірки.
# Додай assert-приклади: порожній трекер, одне завершене з двох занять → 50%, повторне завершення, незалежність об’єктів.
myTracker = StudyTracker("Roman")
alexTracker = StudyTracker("ALex")
myTracker.add_lesson("Python Basics")
myTracker.add_lesson("Functions")
myTracker.add_lesson("Classes")
myTracker.complete_lesson("Python Basics")
myTracker.complete_lesson("Functions")
myTracker.complete_lesson("Classes")
#myTracker.complete_lesson("Classes")
alexTracker.add_lesson("Python Basics")
alexTracker.add_lesson("Functions")
alexTracker.add_lesson("Classes")
# alexTracker.complete_lesson("Python Basics")
myTracker.progress()
myTracker.pending_lessons()
alexTracker.progress()
alexTracker.pending_lessons()
Results saved by the author in Colab
Roman - completed: 3, total: 3, percent: 100.0 Lessons still pending: [] ALex - completed: 0, total: 3, percent: 0.0 Lessons still pending: ['Python Basics', 'Functions', 'Classes']
['Python Basics', 'Functions', 'Classes']
Python · 2
# empthy tracker test
emptyTracker = StudyTracker("Katy")
emptyTracker.progress()
emptyTracker.pending_lessons()Results saved by the author in Colab
Katy - completed: 0, total: 0, percent: 0
AssertionError: Study tracker is empty
Python · 3
# double lesson compleation test
halfTracker = StudyTracker("Pete")
halfTracker.add_lesson("Frist Lesson")
halfTracker.add_lesson("Second Lesson")
halfTracker.complete_lesson("Frist Lesson")
halfTracker.complete_lesson("Frist Lesson")
halfTracker.progress()
halfTracker.pending_lessons()Results saved by the author in Colab
AssertionError: Lesson already finished
Python · 4
# double lesson add test
myErorTracker = StudyTracker("Roman")
myErorTracker.add_lesson("Python Basics")
myErorTracker.add_lesson("Functions")
myErorTracker.add_lesson("Classes")
myErorTracker.add_lesson("Classes")Community reviews
Approved. The PR can be merged.
