CP164 Final: Class Methods

26 views2 pages
13 Jun 2018
School
Course
Professor
Class Methods
Sorting Lists of Objects
Having defined a Student class we could add Student objects to Python lists and tuples.
(Doing so is left as an exercise to you.) A common list method is sort - arranging the
contents of a list in order. However, Python has to know how to compare two objects.
Without comparisons defined, we get errors as in this code:
students = []
# fill students with Student objects
# attempt to sort the lis
students.sort()
Traceback (most recent call last):
students.sort()
TypeError: unorderable types: Student() < Student()
Python sees the Student objects as unorderable because it has no way of comparing these
objects. With the boolean methods correctly defined, however, Python can easily
sort Student objects.We must define the methods.
The __eq__ Method
It is often necessary to be able to compare two objects for equality. Defining
a __eq__ method for a class allows you to compare any two objects of the same class with
the standard == operator, as in this example:
def __eq__(self, other):
"""
-------------------------------------------------------
Compares against another student for equality.
Use: student == other
-------------------------------------------------------
Parameters:
other - other student to compare to (Student)
Returns:
result - True if student IDs match, False otherwise (boolean)
-------------------------------------------------------
"""
result = self.student_id == other.student_id
return result
This is a very simple object comparison, comparing only the student IDs of the two objects.
Thus two student objects, student1 and student2, can be compared in an if statement with:
if student1 == student2:
Unlock document

This preview shows half of the first page of the document.
Unlock all 2 pages and 3 million more documents.

Already have an account? Log in

Document Summary

Having defined a student class we could add student objects to python lists and tuples. (doing so is left as an exercise to you. ) A common list method is sort - arranging the contents of a list in order. However, python has to know how to compare two objects. Without comparisons defined, we get errors as in this code: students = [] Python sees the student objects as unorderable because it has no way of comparing these objects. With the boolean methods correctly defined, however, python can easily sort student objects. we must define the methods. It is often necessary to be able to compare two objects for equality. Defining a __eq__ method for a class allows you to compare any two objects of the same class with the standard == operator, as in this example: def __eq__(self, other): Parameters: other - other student to compare to (student)

Get access

Grade+20% off
$8 USD/m$10 USD/m
Billed $96 USD annually
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
40 Verified Answers

Related Documents