In this module you will look into "interfaces" more closely.
In Python, you can add special methods that start and end with two underscores (__method__(self)) to a class to define how it behaves in certain situations. For example, the __eq__ method can be defined to specify what happens when the == operator is used to compare two instances of your class.
These special methods that allow for specific functionality (such as testing for equivalence, sorting, addition, etc.) are sometimes referred to as protocols. In other languages, such as Java, a similar (but not exactly the same!) language features exists called interfaces. An interface is kind of like a contract: if your class implements an interface, it is guaranteed to have certain methods.
What does this mean in terms of practicality?
+) to work with instances of your class, you have to define a method called __add__ (or if you want to be able to loop over your class, define __iter__)| Method Name | Operator/Function/Control |
|---|---|
__str__(self) |
str(obj) (also print(obj)) |
__eq__(self, other) |
obj == other |
__ne__(self, other) |
obj != other |
__lt__(self, other) |
obj < other |
__gt__(self, other) |
obj > other |
__le__(self, other) |
obj <= other |
__ge__(self, other) |
obj >= other |
__add__(self, other) |
obj + other |
__sub__(self, other) |
obj - other |
__mul__(self, other) |
obj * other |
__div__(self, other) |
obj / other |
__len__(self) |
len(obj) |
__getitem__(self, key) |
obj[key] |
__setitem__(self, key, value) |
obj[key] = value |
__iter__(self) |
for ele in obj: |
__next__(self) |
for ele in obj: |
In the video below, we'll see how we can use these special magic methods to create a class that produces objects that can be looped over: iterable objects.
Iterable object require that two methods be implemented in your class:
__iter____next__When an object is used in a for loop, __iter__ is called. The __next__ method is then repeatedly called on the object returned by __iter__. __next__ is continually called until an exception occurs. A loop can be ended by raising an exception:
raise StopIteration
Note that this does not cause a runtime error, as it's handled by the for loop. Let's see an example!
In addition to creating iterable objects, we can have instances of our class work with + and ==. Check out the video below for examples:
Finally, here's a quick example program that shows how other comparison operators can be defined by implementing __gt__ and __lt__.
Sample Program: Using __eq__, __gt__, and __lt__ to compare instances of a Circle class
Now that you've completed this module, please visit our NYU Classes site and take the corresponding quiz for this module. These quizzes are worth 5% of your total grade and are a great way to test your Python skills! You may also use the following scratch space to test out any code you want.