# import packages
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns; sns.set()
Practice!
# 1) declare them explicitly
x = 0
y = 0
# 2) in a function
# 3) tuple
(0,0)
(0, 0)
A program-defined type is also called a class . A class definition looks like this:
class Point:
"""Represents a point in 2-D space."""
Defining a class named Point creates a class object. Let's assign a point to a variable, called blank
.
blank = Point()
blank
<__main__.Point at 0x1a23cb3240>
The return value is a reference to a Point object, which we assign to blank.
Creating a new object is called instantiation , and the object is an instance of the class.
Just as we could select variables (and functions) from loaded modules/packages, we can assign values to an instance by doing the following
blank.x = 3.0
blank.y = 4.0
Named elements of an object that are assigned values are known as attributes. In other words, they belong to the object.
Practice!
x
the value of blank.x
. Discuss with a partner why you don't think there is a conflict.blank.x ** 2
9.0
You can even pass objects into new functions, where you access those attributes!
print( '%f' % blank.x )
3.000000
def print_point(p):
print('(%g, %g)' % (p.x, p.y))
print_point(blank)
(3, 4)
Practice!
distance_between_points
that takes two Points as
arguments and returns the distance between them.chicken = Point()
chicken.x = 1
chicken.y = 0
nugget = Point()
nugget.x = 4
nugget.y = 4
def dbp(p1, p2):
return ((p1.x - p2.x)**2 + (p1.y - p2.y)**2)**0.5
dbp(nugget, chicken)
5.0
If you wanted to create a class for Rectangles, you could do so by
• Specifying one corner of the rectangle (or the center), the width, and the height. Let's do that now
class Rectangle:
"""Represents a rectangle.
attributes: width, height, (lower left) corner.
"""
# create an instance of a rectangle
box = Rectangle()
# assign width and height to box
box.width = 100.0
box.height = 200.0
# assign a corner as an instance of a point
box.corner = Point()
# assing x, y to the the corner of the box
box.corner.x = 0.0
box.corner.y = 0.0
An object that is an attribute of another object is embedded.
Functions can return instances. For example, find_center takes a Rectangle as an argument 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
temp = find_center(box)
temp.y
100.0