3.2 Creating Data Types
3.2 Creating Data Types
S E D G E W I C K / W A Y N E
SEDGEWICK
ntist WAYNE
Computer Science
ary
A N I N T E R D I S C I P L I N A RY A P P R O A C H
or
d
gs,
of
omputer
C cience Creating Data Types
hem
h.
S
nce
d
wick
ysis
orics;
ver
An Interdisciplinary Approach
ROBERT SEDGEWICK
ANADA
K E V I N WAY N E
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
objects
arrays/lists
Ability to bring life
conditionals and loops to your own
abstractions
3
Object-oriented programming (OOP)
Examples
data type set of values examples of operations
An abstract data type is a data type whose representation is hidden from the client.
To create a data type, you need provide code that In Python, a data-type implementation
• Defines the set of values (class and instance variables). is known as a class.
• Implements operations on those values (methods).
Broad anatomy of a Python class
• Creates and initializes new objects (constructors).
class variables
methods
Methods
• Specialized functions implementing operations.
• Can refer to instance variables.
5
Anatomy of a Python Class
@staticmethod
def topEarner(employees):
topEarner = employees[0]
for employee in employees[1:]:
if employee.salary > topEarner.salary:
topEarner = employee
return topEarner
6
Anatomy of a Python Class
optional class documentation string
class Employee: def main():
'Records basic employee details.' emp1 = Employee("Delboy", 1000)
employeeCount = 0 emp2 = Employee("Rodney",class
600) variable
emp3 = Employee("Boycie", 2500)
def __init__(self, name, salary): employees = [emp1, emp2, emp3]
self.name = name
self.salary = salary emp1.displayDetails() constructor
self.id = Employee.employeeCount instance variables
emp2.displayDetails()
Employee.employeeCount += 1 emp3.displayDetails()
Employee.displayCount()
def displayDetails(self): instance method
print("Top earner is:",
print("Name : ", self.name, "\nID:",self.id, Employee.topEarner(employees).name,"\n")
"\nSalary:", self.salary, "\n")
if __name__ == '__main__':
@classmethod main()
class method
def displayCount(cls):
print("Total Employees: ", cls.employeeCount, "\n")
methods
@staticmethod
static method
def topEarner(employees):
topEarner = employees[0]
for employee in employees[1:]:
if employee.salary > topEarner.salary:
topEarner = employee
return topEarner
Anatomy of a Python Class
A complex number is a number of the form a + bi where a and b are real and
To perform algebraic operations on complex numbers, use real Leonhard Euler A. L. Cauchy
1707−1783 1789−1857
algebra, replace i 2 by −1 and collect terms.
• Addition example: (3 + 4i ) + (−2 + 3i ) = 1 + 7i .
Example: | 3 + 4i | = 5
• Multiplication example: (3 + 4i ) x (−2 + 3i ) = −18 + i .
10
ADT for complex numbers
A complex number is a number of the form a + bi where a and b are real and
complex number 3 + 4i −2 + 2i
Values real part 3.0 −2.0
imaginary part 4.0 2.0
class Complex
#-----------------------------------------
methods
# For testing.
# Create and use some Complex objects.
test client
def main():
z0 = Complex(1.0, 1.0)
z = z0
z = z * z + z0
$ python3 complex.py
z = z * z + z0
-7.0 + 7.0i
print(z)
class variables
Class variables define data-type values that are shared by all objects.
constructor & instance
variables
Instance variables define data-type values that will be specific to each object.
# Construct self with real (re) and imaginary (im) parts imaginary part 4.0 2.0
# both parts default to 0.0
def __init__(self, re=0.0, im=0.0):
self._re = re
self._im = im
13
Complex number data type implementation: methods
14
Complex number data type implementation: methods
# Return True if self and Complex object other are equal, and class variables
# False otherwise.
constructors & instance
def __eq__(self, other): variables
return (self._re == other._re) and (self._im == other._im)
# Return True if self and Complex object other are unequal, and methods
# False otherwise.
def __ne__(self, other):
return not self.__eq__(other)
15
The Mandelbrot set
Examples
• In the set: −0.5 + 0i.
• Not in the set: 1 + i.
Challenge (−0.5, 0)
t zt t zt
(−0.5, 0)
0 −1/2 + 0i 0 1+i
1 −1/4 + 0i 1 1 + 3i
2 −7/16 + 0i 2 −7 + 7i
(-1.5, 1)
Practical issues
• Cannot plot infinitely many points.
• Cannot iterate infinitely many times.
18
Complex number client: Mandelbrot set visualization (helper method)
19
Complex number client: Mandelbrot set visualization
def main():
n = int(sys.argv[1]) # try 80
xc = float(sys.argv[2]) # try -0.5
yc = float(sys.argv[3]) # try 0
size = float(sys.argv[4]) # try 2
limit = 255
win = GraphWin("Mandelbrot Set", n, n)
win.getMouse()
win.close()
20
Mandelbrot Set
21
Mandelbrot Set
ColorMandelbrot
color map
–1.5 0 2
–1.5 0 .002
22
23
Mandelbrot Set
(-1.5, -1)
24
OOP summary
25
You have come a long way
objects
arrays
T A G A T G T G C T A G C
Course goal. Open a whole new world of opportunity for you (programming).
✓ 26
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
Image sources
http://en.wikipedia.org/wiki/Leonhard_Euler#/media/File:Leonhard_Euler.jpg
http://en.wikipedia.org/wiki/Augustin-Louis_Cauchy
http://upload.wikimedia.org/wikipedia/commons/e/e9/Benoit_Mandelbrot_mg_1804-d.jpg
http://upload.wikimedia.org/wikipedia/commons/f/fc/Mandel_zoom_08_satellite_antenna.jpg
http://upload.wikimedia.org/wikipedia/commons/1/18/Mandelpart2.jpg
http://upload.wikimedia.org/wikipedia/commons/f/fb/Mandel_zoom_13_satellite_seehorse_tail_with_julia_island.jpg
http://upload.wikimedia.org/wikipedia/commons/4/44/Mandelbrot_set_à_la_Pop_Art_-_Wacker_Art_Fractal_Generator.jpg
C S . 9 . D . C r e a t i n g D Ts . M a n d e l b r o t
Reading and References
These Slides
• principally based on slides by Robert Sedgewick and Kevin Wayne, and Manrique Mata-Montero
Recommended Reading
• online booksite (Python version) chapter 3
Wider reading and recommended independent learning:
• Elijah Wilson’s suggested structure for a Python class
• Q&A at the end of section 3.2 of the online booksite
• review/learn/re-learn Exception Handling
• there’s a good tutorial at codementor
• or you can also go to the more formal python.org tutorial
• read Designing Data Types from section 3.3 of the online booksite
Activity:
• see the Data Types Practice Exercises in the course shell
28