MCS 275 Spring 2024
Emily Dumas
Reminders and announcements:
open(filename,mode,...)
opens a file and returns a file object. Mode string selects reading ("r"), writing ("w"), ...
Methods of the file object perform input/output (I/O).
Read/write strings to text files (default), bytes to binary files (add "b" in mode).
.close()
a file when finished.
The basics are in Lutz, Chapter 9 and MCS 260 Lec 13 and Lec 14.
def contains_all_digits(x):
s = str(x) # decimal rep of x as a string
for c in "0123456789":
if c not in s:
return False
return True
Interactive use:
>>> contains_all_digits(2*5)
False
>>> contains_all_digits(2**94)
True
The first non-comment statement in any Python function should be a string on a line by itself. That string should describe the function. It is called a docstring.
def contains_all_digits(x):
"Does decimal representation of `x` use all digits 0-9?"
s = str(x) # decimal rep of x as a string
for c in "0123456789":
if c not in s:
return False
return True
Docstrings can also appear as the first statement in a file or in a class definiton.
Use comments, not strings, in all other cases!
A module keeps a bunch of related code in one place; good for reuse and organization. The statement
import modulename
will look for modulename.py
in current directory, or a built-in module with that name, and make its functions, classes, etc. available.
Use modulename.funcname(...)
to call a function in a module.
See Lutz, Chapters 22-23 or MCS 260 Lec 20.
Classes let you define custom types in Python with attributes (data) and methods (behavior).
class Point2:
"""A point in the xy-plane""" # <--- Remember docstring!
def __init__(self,x,y):
"""Initialize new point instance"""
self.x = x # make a new attribute (self.x)
self.y = y # make a new attribute (self.y)
def translate(self,dx,dy):
"""Move the point by a vector (dx,dy)"""
self.x += dx
self.y += dy
p = Point2(1,2) # calls __init__(...)
p.translate(5,0)
print("After moving, p.x is {}".format(p.x)) # will print 6
See Lutz, Chapters 27-28 and MCS 260 Lectures 25, 26, 27, 28.
(End of the tour)
Now we'll start our unit on object-oriented programming (OOP).
We assume knowledge of: Class definitions, creating instances, accessing attributes, calling methods.
We DO NOT assume knowledge of: Subclasses, inheritance, operator overloading.
int
or Point2
24
or Point2(5,7)
In Python, built-in operations are often silently translated into method calls.
e.g. A+B
turns into A.__add__(B)
These special method names begin and end with two underscores (__
). They are used to customize the way your classes work with built-in language features.
Using these to add special behavior for operators like +,-,*
is called operator overloading.
Expression | Special method | |
---|---|---|
A==B | A.__eq__(B) | |
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 | |
---|---|---|
str(A) | A.__str__() | |
len(A) | A.__len__() | |
abs(A) | A.__abs__() | |
bool(A) | A.__bool__() | |
A[k] | A.__getitem__(k) | |
A[k]=v | A.__setitem__(k,v) |
Let's work on
Point2
— point in the plane (a location in 2D)Vector2
— vector in the plane (e.g. the displacement between two points)Difference of two Point2
s is a Vector2
.
Can multiply a Vector2
by a float or add it to a Point2
.
Point2
plus Vector2
is a Point2
.
isinstance(obj,classname)
-- returns bool indicating whether obj
is an instance of the named class (or subclass thereof)NotImplemented
-- Special value that operators should return if the operation is not supported