15.12.2022 Views

Python Eficaz

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

def __init__(self):

self._subjects = {}

def subject(self, name):

if name not in self._subjects:

self._subjects[name] = Subject()

return self._subjects[name]

def average_grade(self):

total, count = 0, 0

for subject in self._subjects.values():

total += subject.average_grade()

count += 1

return total / count

Por fim, escreva um contêiner para todos os estudantes dinamicamente

escolhidos pelos seus nomes.

class Gradebook(object):

def __init__(self):

self._students = {}

def student(self, name):

if name not in self._students:

self._students[name] = Student()

return self._students[name]

O número de linhas de código dessas classes é quase o dobro da implementação

anterior, mas é muito mais fácil de ler. O exemplo a seguir, que faz uso das

classes, é ainda mais claro e com possibilidade de ser estendido.

book = Gradebook()

albert = book.student('Albert Einstein')

math = albert.subject('Math')

math.report_grade(80, 0.10)

# ...

www.full-ebook.com

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!