MCS 260 Fall 2021
Emily Dumas
Key concepts from Lecture 25
"hello"
is an instance of str
)
objname.attrname
.__init__
that is called when a new object is created. Often sets a bunch of attributes using self.attrname = ...
Improve our Rectangle and Circle classes.
Introduce operator overloading.
For both object types:
When Python needs to convert an object to a string, it calls the __str__(self)
method, if it exists.
Define this and return a string that is a human-readable representation of what the object is.
How is A==B
evaluated when A
and B
are objects?
By default, it checks whether the names refer to the same object in memory. This is often not what you want.
Python allows us to specify our own behavior for operators like ==
. This is called operator overloading.
If method A.__eq__
exists, then A==B
evaluates to the return value of A.__eq__(B)
.
The built-in function isinstance(obj,cls)
returns a bool indicating whether obj
is an instance of the class cls
, e.g. isinstance(7,int)
Using it sparingly. Remember, Python recommends EAFP rather that LBYL in most cases.
EAFP = Easier to Ask Forgiveness than Permission
LBYL = Look Before You Leap
Many operators can be overloaded, including:
Expression | Special method | |
---|---|---|
A+B | A.__add__(B) | |
A-B | A.__sub__(B) | |
A*B | A.__mul__(B) | |
A/B | A.__truediv__(B) | |
A**B | A.__pow__(B) |
List of many more in the Python documentation.
Expression | Actually calls | |
---|---|---|
len(A) | A.__len__() | |
bool(A) | A.__bool__() | |
A[k] | A.__getitem__(k) | |
A[k]=v | A.__setitem__(k,v) |