MCS 260 Fall 2020
Emily Dumas
It is common to write assignments that apply one operation to an existing variable and assign the result to that variable.
Example:
x = x + 25
There is a shorter syntax for this:
x += 25
Not repeating the name x
twice can help avoid errors.
Old way | New way | |
---|---|---|
a = a + b | a += b | |
a = a - b | a -= b | |
a = a * b | a *= b | |
a = a / b | a /= b | |
a = a ** b | a **= b | |
a = a % b | a %= b | |
a = a // b | a //= b |
Key concepts from Lecture 23
"hello"
is an instance of str
)
objname.attrname
.__init__
that is called when a new object is created.Improve our Rectangle and Circle classes.
Put them in a module.
Introduce operator overloading.
Result: geom.py
(Also see the updated geom.py developed in subsequent lectures.)
For both object types:
The __repr__ method converts an object to a string that should represent it perfectly; i.e. the object can be completely recovered from the data in the string.
Contrast to __str__, which emphasizes human readability (maybe at cost of ambiguity).
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,cl)
returns a bool indicating whether obj
is an instance of the class cl
.
Using it sparingly. Often it is better to attempt to use expected behavior or attributes, and let an exception detect any problem.
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) |