Hejka, mam takie pytanie. Mam taką klasę w Pythonie:
class SubjectTest(abc.ABC):
def __init__(self, questions=None, date=None, num_questions=10):
self.questions = [] if questions is None else questions
self.points = 0
self.date = date
self.num_questions = num_questions
def add_question(self, question):
self.questions.append(question)
def add_questions(self, *questions):
self.questions.extend(questions)
def max_points(self):
return len(self.questions)
def percent_progress(self):
return self.points / self.max_points() * 100
def grade(self):
return to_grade(self.percent_progress())
# ...
class Subject:
def __init__(self, name, tests=None):
self.name = name
self.tests = [] if tests is None else tests
def add_test(self, test):
self.tests.append(test)
def remove_test(self, test):
self.tests.remove(test)
def take_test(self, test):
if test not in self.tests:
raise ValueError(f'Error: given test is not available for the subject "{self.name}".')
test.quiz()
def grades(self):
return [test.grade() for test in self.tests]
def points(self):
return [test.points for test in self.tests]
def average_percentage(self):
return sum(test.points for test in self.tests) / sum(test.max_points() for test in self.tests)
def average_grade(self):
return to_grade(self.average_percentage())
Chcę, aby można było mieć dostęp do metod average_percentage, average_grade itd. w ten sposób:
maths = Subject(name='Matma')
maths.take_test(maths_exam)
print(maths.average_grade) # maths.average_grade zamiast maths.average_grade()
Czy użycie dekoratora @property w tym celu to dobry sposób? Chcę to po to zrobić ponieważ w klasie SubjectTest mam takie publiczne zmienne jak points, date, num_questions i takie metody jak grade, max_points, które pobierają dane na podstawie właściwości tylko w odpowiednio przetworzonej formie (grade w tym wypadku konwertuje zdobyte punkty na stopień) i chcę ujednolicić kod, nie chcę mieszać wywołań funkcji i odwołań do zmiennych.