Das einzig wirklich interessante scheint mir die Alter/Geburtstag-Redundanz zu sein, die man beseitigen sollte. Wobei die Lösung dafür im folgenden Code nicht ganz fehlerfrei ist:
Code: Alles auswählen
#!/usr/bin/env python3
from datetime import date as Date
from enum import Enum, auto
from attr import attrib, attrs
from prettyprinter import install_extras, pprint
@attrs
class Person:
given_name = attrib()
surname = attrib()
date_of_birth = attrib()
@property
def age(self):
birth_year = self.date_of_birth.year
today = Date.today()
return (
today.year
- birth_year
- int(today.replace(year=birth_year) < self.date_of_birth)
)
@attrs
class Professor(Person):
field = attrib()
classification = attrib()
@attrs
class Student(Person):
matriculation_number = attrib()
semester = attrib()
ects = attrib()
class Degree(Enum):
BACHELOR = auto()
MASTER = auto()
@attrs
class DegreeProgramme:
name = attrib()
type = attrib()
professors = attrib(factory=list)
students = attrib(factory=list)
def add_professor(self, professor):
self.professors.append(professor)
def add_student(self, student):
self.students.append(student)
@attrs
class University:
name = attrib()
city = attrib()
degree_programmes = attrib(factory=list)
def add_degree_programme(self, degree_programme):
self.degree_programmes.append(degree_programme)
def main():
install_extras(["attrs"])
professor = Professor(
"Ponder",
"Stibbons",
Date(1960, 7, 25),
"Inadvisably Applied Magic",
"X5",
)
student = Student("Eskarina", "Smith", Date(1998, 2, 18), 6238, 42, 23)
print(professor.age)
print(student.age)
degree_programme = DegreeProgramme("High Wizard", Degree.MASTER)
degree_programme.add_professor(professor)
degree_programme.add_student(student)
university = University("Unseen University", "Ankh-Morpork")
university.add_degree_programme(degree_programme)
pprint(university)
if __name__ == "__main__":
main()
Ausgabe:
Code: Alles auswählen
59
22
University(
name='Unseen University',
city='Ankh-Morpork',
degree_programmes=[
DegreeProgramme(
name='High Wizard',
type=Degree.MASTER,
professors=[
Professor(
given_name='Ponder',
surname='Stibbons',
date_of_birth=datetime.date(1960, 7, 25),
field='Inadvisably Applied Magic',
classification='X5'
)
],
students=[
Student(
given_name='Eskarina',
surname='Smith',
date_of_birth=datetime.date(1998, 2, 18),
matriculation_number=6238,
semester=42,
ects=23
)
]
)
]
)