MCS 260 Fall 2021
Key concepts from Lecture 25
"hello"is an instance of
__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.
A==B evaluated when
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.
A.__eq__ exists, then
A==B evaluates to the return value of
The built-in function
isinstance(obj,cls) returns a bool indicating whether
obj is an instance of the class
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:
List of many more in the Python documentation.