Page 172 - think python 2
P. 172
150
Chapter15. Classesandobjects
box
Point
Rectangle
width 100.0 height 200.0 corner
class Rectangle:
Figure 15.2: Object diagram.
"""Represents a rectangle.
attributes: width, height, corner.
"""
The docstring lists the attributes: width and height are numbers; corner is a Point object that specifies the lower-left corner.
To represent a rectangle, you have to instantiate a Rectangle object and assign values to the attributes:
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
The expression box.corner.x means, “Go to the object box refers to and select the attribute named corner; then go to that object and select the attribute named x.”
Figure 15.2 shows the state of this object. An object that is an attribute of another object is embedded.
15.4 Instances as return values
Functions can return instances. For example, find_center takes a Rectangle as an argu- ment and returns a Point that contains the coordinates of the center of the Rectangle:
def find_center(rect):
p = Point()
p.x = rect.corner.x + rect.width/2
p.y = rect.corner.y + rect.height/2
return p
Here is an example that passes box as an argument and assigns the resulting Point to center:
>>> center = find_center(box)
>>> print_point(center)
(50, 100)
x 0.0
y 0.0