|
| 1 | +class Student: |
| 2 | + """ |
| 3 | + a class to demonstrate how to define |
| 4 | + a custom class that can be used in a set or a dict |
| 5 | + (and that can be sorted too, btw) |
| 6 | +
|
| 7 | + try and run it without the last 3 dunder methods to see what happens |
| 8 | + """ |
| 9 | + |
| 10 | + def __init__(self, first_name, last_name, grade=None): |
| 11 | + self.first_name = first_name |
| 12 | + self.last_name = last_name |
| 13 | + self.grade = grade |
| 14 | + |
| 15 | + # pretty print |
| 16 | + def __repr__(self): |
| 17 | + return f"<{self.first_name} {self.last_name} ({self.grade})>" |
| 18 | + |
| 19 | + # hash on first and last name |
| 20 | + def __hash__(self): |
| 21 | + return hash( (self.first_name, self.last_name) ) |
| 22 | + |
| 23 | + # the protocol for hashable objets require this to be defined too |
| 24 | + def __eq__(self, other): |
| 25 | + return self.first_name == other.first_name and self.last_name == other.last_name |
| 26 | + |
| 27 | + # sort on grades |
| 28 | + def __lt__(self, other): |
| 29 | + return self.grade < other.grade |
| 30 | + |
| 31 | +#### usage |
| 32 | + |
| 33 | + |
| 34 | +print(10*'=', 'a set containing students') |
| 35 | + |
| 36 | +s1 = Student('John', 'Doe', 12) |
| 37 | +s2 = Student('Jane', 'Doe', 15) |
| 38 | +s3 = Student('Jean', 'Dupont', 11) |
| 39 | +s4 = Student('Marie', 'Martin', 14) |
| 40 | + |
| 41 | +# can use a set to store students |
| 42 | +students = {s1, s2, s3} |
| 43 | + |
| 44 | +print(f"{s1 in students=}") |
| 45 | +print(f"{s4 in students=}") |
| 46 | + |
| 47 | +s1.grade = 13 |
| 48 | +print(f"after grade change {s1 in students=}") |
| 49 | + |
| 50 | + |
| 51 | + |
| 52 | +print(10*'=', 'dict works too') |
| 53 | + |
| 54 | +grades_by_students = {s: s.grade for s in students} |
| 55 | +print(f"{grades_by_students[s2]=}") |
| 56 | + |
| 57 | +# this one would not work if we had not defined __hash__ and __eq__ |
| 58 | +s1bis = Student('John', 'Doe') |
| 59 | +print(f"{s1bis in students=} and {grades_by_students[s1bis]=}") |
| 60 | + |
| 61 | + |
| 62 | +print(10*'=', 'sorting') |
| 63 | + |
| 64 | +students = {s1, s2, s3, s4} |
| 65 | +print(f"{sorted(students)=}") |
0 commit comments