Xiaojuan Cai Computational Thinking 1 Lecture 9 Defining Classes Xiaojuan Cai (蔡小娟)...
-
Upload
priscilla-anthony -
Category
Documents
-
view
232 -
download
0
Transcript of Xiaojuan Cai Computational Thinking 1 Lecture 9 Defining Classes Xiaojuan Cai (蔡小娟)...
Xiaojuan Cai Computational Thinking 1
Lecture 9
Defining Classes
Xiaojuan Cai(蔡小娟)
Fall, 2015
Xiaojuan Cai Computational Thinking 2
Objective• To appreciate how defining new classes can provide
structure for a complex program.
• To understand the concept of encapsulation and
how it contributes to building modular and
maintainable programs.
• To be able to write programs involving simple class
definitions.
• To understand the concepts of encapsulation,
polymorphism and inheritance
Xiaojuan Cai Computational Thinking 3
Roadmap
• Motivating example: cannon ball
• Define new classes
• Objects and encapsulation
• OO method
Xiaojuan Cai Computational Thinking 4
Review: objects
• Class: the template of objects, defining
• the types of data an object can have
• and operations it can do.
• Object: the instance of some class
• Objects of the same class can have different data,
• E.g., Student A and B have different ID numbers.
• Message = operation = methods
Xiaojuan Cai Computational Thinking 5
Review: objects
• Create an object from a class:
<objname> =
<classname>(<param1>,<param2,…>)
• Send message to objects:
<objname>.<methodname>(<param1>,
<param2>,…)
Xiaojuan Cai Computational Thinking 6
Review: objects• Instance variables: the information stored inside
the object.
• Methods: the operations (functions) “living” inside
the object.
• Attributes: the instance variables and methods.
CircleInstance variables: center, radiusMethods: draw(), getCenter(), ….
Xiaojuan Cai Computational Thinking 7
Motivating example• Simulate the flight of a cannonball or other
projectile.
• Input:
• launch angle (in degrees),
• the initial velocity (in meters per second),
• and the initial height (in meters) of the cannonball
• Output
• the distance that the projectile travels
Xiaojuan Cai Computational Thinking 8
Algorithm
• By calculus, we can have a formula.
• By simulation, a little geometry, and
some facts:
• The acceleration of gravity = 9.8 m/s/s.
• Distance = velcocity * time
• No wind
Xiaojuan Cai Computational Thinking 9
Algorithm1 – cball1.py• Input vel, angle, h0, inv
• theta = angle*(pi/180), xvel = vel *
sin(theta), yvel = vel * cos(theta), x = 0, y =
h0
• While y >= 0
• Compute (x,y,yvel) after an inv
• x = x + xvel*inv, yvel’ = yvel – 9.8*inv, y = y
+ inv*(yvel+yvel’)/2.0, yvel = yvel’
• Output x
Xiaojuan Cai Computational Thinking 10
Algorithm2 – cball2.py• Modualizing
angle, vel, h0, inv = getInputs()
x,y= 0, h0
xvel, yvel = getXYComponents(vel, angle)
while y >= 0:
x, y, yvel = updateCannonBall(inv, x, y, xvel, yvel)
print "\nDistance traveled: %0.1f meters." % (xpos)
Xiaojuan Cai Computational Thinking 11
Algorithm2 – cball2.py• Modualizing
angle, vel, h0, inv = getInputs()
x,y= 0, h0
xvel, yvel = getXYComponents(vel, angle)
while y >= 0:
x, y, yvel = updateCannonBall(inv, x, y, xvel, yvel)
print "\nDistance traveled: %0.1f meters." % (xpos)
5 arguments, 3 return values!
Xiaojuan Cai Computational Thinking 12
Algorithm3 – cball3.py• Make the cball from the class Projectile
• Since all the projectile compute new positions the same way!
• angle, vel, h0, inv = getInputs()
cball = Projectile(angle, vel, h0)
while cball.getY() >= 0:
cball.update(inv)
print "\nDistance traveled: %0.1f meters." %
(cball.getX())
• More readable and understandable!
Xiaojuan Cai Computational Thinking 13
The Projectile class• __init__ method : initialize the instance variables
of cball.
def __init__(self, angle, velocity,
height):
self.xpos = 0.0
self.ypos = height
theta = pi * angle / 180.0
self.xvel = velocity * cos(theta)
self.yvel = velocity * sin(theta)
Xiaojuan Cai Computational Thinking 14
Multi-sided dice
• Some games use special dice with a
different number of sides.
• Each MSDie object will know two things:
• How many sides it has.
• It’s current value
• Interfaces
Xiaojuan Cai Computational Thinking 15
Multi-sided dice>>> die1 = MSDie(6)>>> die1.getValue()1>>> die1.roll()>>> die1.getValue()5>>> die2 = MSDie(13)>>> die2.getValue()1>>> die2.roll()>>> die2.getValue()9>>> die2.setValue(8)>>> die2.getValue()8
Xiaojuan Cai Computational Thinking 16
Roadmap
• Motivating example: cannon ball
• Define new classes
• Objects and encapsulation
• OO methods
Xiaojuan Cai Computational Thinking 17
Class definition• Class definitions have the form
class <class-name>:
<method-definitions>
• The first parameter of a method is always named self,
which is a reference to the object on which the method is
acting.
• die1.setValue(8) -> setValue(self, 8)
• __init__
• Instance variables are generated dynamically
Xiaojuan Cai Computational Thinking 18
The Projectile class
def update(self, time):
self.xpos = self.xpos + time *
self.xvel
yvel1 = self.yvel - 9.8 * time
self.ypos = self.ypos + time *
(self.yvel + yvel1) / 2.0
self.yvel = yvel1
Xiaojuan Cai Computational Thinking 19
Roadmap
• Motivating example: cannon ball
• Define new classes
• Objects and encapsulation
• OO methods
Xiaojuan Cai Computational Thinking 20
Encapsulation• The separation of what objects can do and how
they are implemented is called encapsulation.
• Advantages:
• The outside of the class only cares about the interface
• The update and improvements can be done
independently.
• Without worrying about “break” other parts.
Xiaojuan Cai Computational Thinking 21
Algorithm4 – cball4.py• Put classes in modules.
• Import them when needed. (Code reusable)
• Module documentations, “““docstring “““• Ordinary comments are ignored by Python
• Docstrings are accessible in a special attribute called __doc__.
• >>> import random
>>> print random.random.__doc__
Xiaojuan Cai Computational Thinking 22
Roadmap
• Motivating example: cannon ball
• Define new classes
• Objects and encapsulation
• OO methods
Xiaojuan Cai Computational Thinking 23
OOD• Object-oriented design (OOD): data-centered
view of computing:
• The essence of OOD is describing a system in
terms of magical black boxes and their interfaces.
• The separation of concerns of “What” and “How”
makes the design of complex systems possible.
Xiaojuan Cai Computational Thinking 24
The process of OOD
1. Look for object candidates
• Things that can be represented as
primitive data types (numbers or strings)
are not important object candidates.
• Things to look for: a grouping of related
data items (e.g., point coordinates,
employee)
Xiaojuan Cai Computational Thinking 25
The process of OOD
2. Identify instance variables
• Some object attributes will have
primitive data types, while others
may be complex types (other useful
objects/classes).
Xiaojuan Cai Computational Thinking 26
The process of OOD
3. Think about interfaces
• Consider the verbs in the problem
statement
• List the methods that the class will require.
• Remember: all of the manipulation of the
object’s data should be done through the
methods you provide.
Xiaojuan Cai Computational Thinking 27
The process of OOD
4. Refine the non-trivial methods
• Use top-down design and stepwise
refinement to flesh out the details of
the more difficult methods
Xiaojuan Cai Computational Thinking 28
The process of OOD
5. Design iteratively
• No one designs a program top to bottom
in a linear, systematic fashion.
• Good design involves a lot of trial and
error!
• Well-designed programs are probably not
the result of a first try.
Xiaojuan Cai Computational Thinking 29
The process of OOD
6. Keep it simple
• At each step in the design, try to
find the simplest approach that will
solve the problem.
Xiaojuan Cai Computational Thinking 30
Case study
•高考成绩单管理系统• 每年高考结束后,考生的成绩会寄送到家里。请设计一个高考成绩单管理系统,能够
• 输入准考证号码,查询该学生的各科成绩
• 将所有学生的家庭地址、各科成绩以某种形式写到文件中,以供邮寄成绩单。
Xiaojuan Cai Computational Thinking 31
1. Look for object candidates
• ScoreManagement
• Students
• HomeAddress
• Score
Xiaojuan Cai Computational Thinking 32
2. Identify instance variables
• ScoreManagement
• students (a list of Student)
• Student
• name (string), regNo (long), homeAddress (HomeAddress),
scores (a list of Score)
• HomeAddress
• postcode (int), address1 (string), address2 (string)
• Score
• subject (string), grade (float)
Xiaojuan Cai Computational Thinking 33
3. Think about interfaces
• ScoreManagement
• search(regNo), printAll()
• Student
• getName(), getRegNo(), getHomeAddress(), getScore()
• HomeAddress
• __str__()
• Score
• __str__()
Xiaojuan Cai Computational Thinking 34
4. Refine non-trivial methods
• search(regNo):
• for s in students:
• if s.getRegNo() == regNo: return s
• …
Xiaojuan Cai Computational Thinking 35
5. Design iteratively
• homeAddress as a tuple?
• scores as a dictionary?
• Keep it simple and elegant!
Xiaojuan Cai Computational Thinking 36
OO concepts
• OO is comprised of three
principles:
• Encapsulation (封装 )
• Polymorphism (多态 )
• Inheritance (继承 )
Xiaojuan Cai Computational Thinking 37
Encapsulation• The packaging of data with a set of operations that
can be performed on the data is called encapsulation.
• Encapsulation separates the concerns of “what” vs.
“how”. The implementation of an object is
independent of its use.
• Advantages:
• Easy to maintain
• Code reuse
Xiaojuan Cai Computational Thinking 38
Polymorphism• Literally, polymorphism means “many forms.”
• In OO, it means what an object does in
response to a method call depends on the type
or class of the object.
• With polymorphism, a given line in a program
may invoke a completely different method.
Xiaojuan Cai Computational Thinking 39
Polymorphism• Suppose you had a list of graphics objects – a
mixture of Circle, Rectangle, Polygon, etc.
• You could draw all the items with this simple code:for obj in objects:
obj.draw(win)
• Advantages: flexibility for each object to perform
an action just the way that it should be performed
for that object.
Xiaojuan Cai Computational Thinking 40
Inheritance• The idea behind inheritance is that a new class
can borrow behavior from another class.
• The “borrowing” class is called a subclass, and
the other (being borrowed) is called a
superclass.
• Advantages:
• code reuse
• flexibility
Xiaojuan Cai Computational Thinking 41
Inheritance• In the score management system, students may
come from China or US. The forms of home
addresses are different from each other.
• ChinaStudent(Student), USStudent(Student)
• We only need to re-implement printHomeAddress()
for USStudent
• Inheritance + polymorphism are most important
characteristics of OOD and OO languages.
Xiaojuan Cai Computational Thinking 42
Conclusion• Why classes: Modularity and encapsulation
• Class:
• How to design classes
• Instance variable
• Message
• Class definitions:
• Instance variables are generated dynamically
• Messages always have a parameter self
• OOD and three main concepts for OO