In-class notes for 04/11/2014
CS 121B (CS1), Spring 2014
______
Submitted questions on assignments and technology
Upcoming
-
Three remaining events, all in Tomson 280
Friday 3:00pm speaker -- up to 2 point EC for a half-page response
Friday 4:30pm speaker -- up to 2 point EC for a half-page response
Friday 7:30pm CS speaker -- up to 4 points EC for a half-page response
cs1S14 username
, e.g.,cs1S14 rab
.
Classes we have seen so far
An object is a programming entity that has state variables (memory locations, to hold data) and methods (operations on the state variables)
A class is a type of object.
Objects in the same class have the same state-variable structure, and the same collection of methods.
Return value from
type()
indicates the class of an objectClasses we have seen that are built-in to Python3:
list
. Example method:sort()
str
. Many example methods, such assplit()
,strip()
, andlower()
tuple
. Example method:count(val)
dict
. Example method:keys()
int, float, bool,
andrange
are also implemented as classes in Python3, although we seldom call their methods(-4.0).isinteger()
-->True
Other classes we have seen that are not built-in, but are defined in standard Python3 modules:
turtle.Turtle
. Many methods such asforward()
,left()
,pencolor()
turtle._Screen
. Methods such asexitonclick()
Classes we have seen that are not built-in and are not defined in standard Python3 modules:
cImage.Image
. Methods such asdraw()
,setPixel()
,getHeight()
cImage.ImageWin
. Methods such asexitonclick()
A programmer-defined class (not built-in, not defined in a standard module):
Account
, defined by~cs121/Account.py
, spec in this link. Methods such asgetBalance()
,deposit()
Defining classes
Memory diagram of an
Account
objectObjects in the same class have the same state-variable structure, although each has its own separate memory locations.
Syntax of a class definition
Exercise
Exercise 1:
Define a Python3 class
Animal
that satisfies the following spec:- 3 state variables:
name
,species
,fact
- Constructor should have 3 args (plus
self
) - Methods:
getName()
,getSpecies
,getFact()
,setFact()
Also, write code to accomplish the following:
- Construct two animal objects (e.g.,
lion
anddog
) - Retrieve value of the
name
state variable for first object - Retrieve value of the
species
state variable for second object - Change the value of the
fact
state variable for second object, then retrieve the new value
- 3 state variables:
Submitted questions on readings
< >