Module 5
Module 5
list or tuple.
as objects.
A programmer-defined type is also called a
class.
A class definition looks like this:
class Point:
interchangeable.
Attributes
We can assign values to an instance using dot
notation:
>>> blank.x = 3.0
>>> blank.y = 4.0
A state diagram that shows an object and its
def print_point(p):
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
Instances as return values
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2
return p
>>> center = find_center(box)
>>> print_point(center)
(50, 100)
Objects are mutable
box.width = box.width + 50
box.height = box.height + 100
def grow_rectangle(rect, dwidth, dheight):
rect.width += dwidth
rect.height += dheight
>>> box.width, box.height
(150.0, 300.0)
>>> grow_rectangle(box, 50, 100)
>>> box.width, box.height
(200.0, 400.0)
Copying
Aliasing can make a program difficult to read
because changes in one place might have
unexpected effects in another place. It is hard to
keep track of all the variables that might refer to
a given object.
class Time:
"""Represents the time of day.
attributes: hour, minute, second""“
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
Object diagram
Pure functions
The function creates a new Time object, initializes its
attributes, and returns a reference to the new object.
This is called a pure function because it does not
modify any of the objects passed to it as arguments
and it has no effect, like displaying a value or getting
user input, other than returning a value.
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
Once you are convinced they are correct, you
can use them to rewrite add_time:
def print_time(time):
print('%.2d:%.2d:%.2d' % (time.hour, time.minute,
time.second))
>>> end.Is_after(start)
True
The __init_ _ method
The init method (short for “initialization”) is a special
method that gets invoked when an object is
instantiated. Its full name is __init__.
self.second)
'spam']
>>> histogram(t)
{'bacon': 1, 'egg': 1, 'spam': 4}
Since Time objects provide an add method,
they work with sum:
>>> t1 = Time(7, 43)
>>> t2 = Time(7, 41)
>>> t3 = Time(7, 37)
>>> total = sum([t1, t2, t3])
>>> print(total)
23:01:00
The best kind of polymorphism is the
unintentional kind, where you discover that a
function you already wrote can be applied to a
type you never planned for.
Debugging
It is legal to add attributes to objects at any
point in the execution of a program, but if
you have objects with the same type that
don’t have the same attributes, it is easy to
make mistakes.
def print_attributes(obj):
for attr in vars(obj):
print(attr, getattr(obj, attr))