| CS 331 Spring 2009 > Additional Lecture Notes for Friday, April 3, 2009 |
Python overloads operators using member functions named “__NAME__”, where NAME is the name corresponding to the operator. For example, the binary + operator’s name is add, while the += operator is called iadd. (I have read that the “i” stands for “in place”.)
For example, here is a silly numeric class that can add.
class Addable:
def __init__(self, n):
self.n = n
def __add__(self, other):
return Addable(self.n + other.n)
def __iadd__(self, other):
self.n += other.n
return self
def __str__(self):
return "Addable:" + str(self.n)
The __str__ member function allows string conversion using the str built-in. It also allows printing using the print built-in. Here is some example code using the above class.
x = Addable(3) y = Addable(4) x += y print(x) # Prints "Addable:7" z = Addable(5) print(y+z) # Prints "Addable:9"
Interestingly, the += operator still works if we do not define member function __iadd__. In this case, Python will convert “x += y” to “x = x + y”.
As we discovered in class, the reverse does not hold: if you do not write __add__, then you do not get the binary + operator, even if you do define __iadd__.
Unlike C++, the assignment operator in Python (=) does not call a function. Instead, it makes the left-hand-size refer to the right. This can have unexpected effects if the value in question is mutable.
a = [1,2,3] # Lists are mutable b = a a[1] = 999 print(b) # Prints "[1, 999, 3]"
This raises a question: if assignment does not copy, then how do you copy in Python? It turns out that there is a copy library. It contains functions copy, which does a shallow copy, and deepcopy, which does a deep copy.
import copy # for copy.copy, copy.deepcopy a = [1,2,[3,4,5]] b = a c = copy.copy(a) d = copy.deepcopy(a) a[0] = 999 # Set the 1 to 999 a[2][1] = 999 # Set the 4 to 999 print(a) # Prints "[999, 2, [3, 999, 5]]" print(b) # Prints "[999, 2, [3, 999, 5]]" print(c) # Prints "[1, 2, [3, 999, 5]]" print(d) # Prints "[1, 2, [3, 4, 5]]"
| CS 331 Spring 2009: Additional Lecture Notes for Friday, April 3, 2009 / Updated: 3 Apr 2009 / Glenn G. Chappell / ffggc@uaf.edu |
|