Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A student is a name and a list of marks. Explain in two or three sentences why a Student class can be better than a dictionary and a separate function average(student).
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, compare your working with the solution.
Plan. Think about where the data and the actions live, and about the rules.
With a dictionary and a function, the data is in one place and the action is in another. Nothing links them, so the function can be called with a dictionary that has no marks, or with marks that are text, and the mistake shows up late and far from its cause.
With a class, the marks and the average method live together, so student.average() always works on the marks of that student. The class can also check the marks when the student is made, for example refuse a mark outside 0 to 100, so a bad object can never exist.
As a program grows, objects that look after their own data keep the program tidy.
Answer: The data and the actions stay together, and the class can protect its data with rules.
Log in to join the discussion.
Loading…