Objects as records
After this: Keep a list inside an object and objects inside a list, choose between a class and a dictionary, and read the Java frame at last.
On this page · 6 sections · 3 checks
A school keeps a card for each student: the name at the top, and a column of marks under it. The cards sit in a drawer. To find every student's average, you take the cards one by one, add up the marks on the card, and divide.
An object can be a card like that: a few named fields that belong together. This lesson uses objects as records, puts a list inside an object and objects inside a list, and then, at last, explains the Java frame.
A list inside an object
A field can hold any value, a list included. Student has a name and a list of marks, and one method, average, which adds up the marks and divides by how many there are. The marks belong to the object, so average needs no parameters: self.marksmarks is the list of the student it was called on.
The program makes two students, puts them in a list, and goes through the list with a loop. Each turn of the loop puts one student in s, and s.average() opens a frame with selfthis holding that student.
- Run the programRun it and step through. Two Student objects are made, each with a list of marks inside it. Then the loop takes each one in turn, and average opens a frame with self (this in Java) holding that student.
class Student: def __init__(self, name, marks): self.name = name self.marks = marks
def average(self): return sum(self.marks) / len(self.marks)
ana = Student("Ana", [80, 90])ben = Student("Ben", [70, 75])students = [ana, ben]for s in students: print(s.name, s.average())run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
- Ana's marks are 80 and 90. The sum is 170, and divided by two that is
85.0. - Ben's marks are 70 and 75. The sum is 145, and divided by two that is
72.5.
The band cuts the box students short, because two whole objects do not fit in it. The box s shows the student of the current turn in full.
A class or a dictionary?
The same data fits in a dictionary: the keys "name" and "balance", with Ana and 100 as the values. Here are both shapes side by side, with one field read each way.
class Account: def __init__(self, name, balance): self.name = name self.balance = balance
a = Account("Ana", 100)d = {"name": "Ana", "balance": 100}print(a.balance)print(d["balance"])run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Both print 100. So when is a class the better shape?
- Use a dictionary when the keys are data: words to count, names to look up, and you do not know in advance which keys there will be.
- Use a class when every object has the same few fields, and above all when the data has actions. A dictionary cannot hold a
depositthat knows its own balance. An object can.
The Java frame, explained at last
From the very first program, every Java file has had the same lines around it: public class Main { and public static void main(String[] args) {. You can now read them.
Main is a class, like Account. main is its one method, the one Java runs first. void, as in Functions, means that it hands nothing back. String[] args is a list of words typed after the program's name, which these tutorials never use. And static means: this method belongs to the class itself, not to one object. No object of Main is ever made, so there is nothing to put in this, and main has to be static. Every function you wrote next to it carried static for the same reason: a static method has no object, so the methods it calls by their plain names must be static too. deposit has no static, because it works on one account, the one in this.
Run it
Add a third student with three marks, put it in the list, and run again.
Check yourself
Two teams in a list, each with its own scores. What does this print?
class Team: def __init__(self, name, scores): self.name = name self.scores = scores
def total(self): return sum(self.scores)
teams = [Team("Red", [3, 4]), Team("Blue", [1, 1, 1])]for t in teams: print(t.name, t.total())import java.util.ArrayList;import java.util.List;
class Team { String name; ArrayList<Integer> scores;
Team(String name, ArrayList<Integer> scores) { this.name = name; this.scores = scores; }
int total() { int sum = 0; for (int s : scores) { sum = sum + s; } return sum; }}
public class Main { public static void main(String[] args) { ArrayList<Team> teams = new ArrayList<>(); teams.add(new Team("Red", new ArrayList<>(List.of(3, 4)))); teams.add(new Team("Blue", new ArrayList<>(List.of(1, 1, 1)))); for (Team t : teams) { System.out.println(t.name + " " + t.total()); } }}In Java, every function in the earlier tutorials was written with static, and deposit is written without it. What does static mean?
A program keeps two hundred bank accounts, each with a name and a balance, and must deposit into them and withdraw from them with the rule that a withdrawal is refused when the money is not there. Which shape fits best?
Honesty notes
- Keep a list inside an object, and compute something from it in a method of that object.
- Put objects in a list and go through them with a loop, calling the same method on each.
- Choose between a class and a dictionary for a set of data, and say why a class fits when the data has actions.
- Say what the Java frame means: Main is a class, main is its one method, and static means a method belongs to the class rather than to one object.