Victor Norman CS104 Records In Excel you can create rows that represent individual things with each column representing some property of that thing Eg each row could represent a student with ID: 413883
Download Presentation The PPT/PDF document "Classes and Objects, Part 1" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Classes and Objects, Part 1
Victor Norman
CS104Slide2
“Records”
In Excel, you can create rows that represent individual things, with each column representing some property of that thing.
E.g., each row could represent a student, with
column 1: student id
column 2: student last name
column 3: student first name
column 4:
gpa
column 5: how much tuition is owed…
Each row *must* stay together: don’t want to move values from one row to another.Slide3
How to do this in python?
How could we make a collection of items/values that belong together?
Have to use a composite data type.
i.e., lists or tuples.
Question: does order of
items/values
really matter?Slide4
Ancient History (last Thursday)
A card is a tuple with 2 parts, a suit (one of “s”, “d”, “c”, “h”) and a number (2 – 14).
We create a card by making a tuple.
We access the suit via card[0] and number via card[1].
W
hat is good and what is bad about this implementation?Slide5
What
types
of variables can we make?
Is this good enough?
Wouldn’t it be nice if we could create our own types?Slide6
Using a List/Tuple
to store data
If we want to group together data into one structure/record
, we could use a list (or a tuple):
student1 = [‘Dan’, 4, [80, 82, 6]]
student2 = [‘Paula’, 2, [49, 90, 87]]
Disadvantages:
Looking at the list, cannot tell what the “fields” mean. (What is the 1th item?)
List has order, which we don’t need.Slide7
One fix: use functions
We could create functions to extract and name the data:
def
getName
(stud):
return stud[0]
def
getYear
(stud):
return stud[1]
def
getLowestGrade
(stud):
# code here to iterate through stud[2]
# assume we’ve created student1 and student2, both lists
# with the proper format.
name =
getName
(student1)
year =
getYear
(student2)
if
getLowestGrade
(student1) >
getLowestGrade
(student2):
print(“Good job, student!”)Slide8
Thoughts on this…
It is a big improvement, but…
Change the order of the data in the list
you have to change the function code.
What is stud[1]? The code in the functions is still unreadable. (First grade is stud[2][0].)
You cannot enforce that users of this list will use the provided functions to get the values.
First parameter to every function is the student data structure.Slide9
Better: classes and objects
a
class
is like a recipe (or template).
you don't eat the recipe, right?
an
object
(or
instance
) is
an
instantiation
of that class
that's what you eat.
Each
class is defined by its
name
attributes
(characteristics, properties, fields)
methods
(functions)
We already know how to define functions, but we don’t know how to
group
them together, to say, “These belong together, and they operate on this data.”Slide10
Big Question
What defines a type
?
Data + operations
what you can store.
what you can do to or with it.Slide11
Examples
list
is a built-in python
class
(or type).
holds ordered objects.
has
methods
defined:
append
(),
extend
(),
index
(), [], [
x:y
], +,
pop
(), etc.
Instantiate
it as often as you want to make individual
objects
.
girls = [‘Kim’, ‘Taylor’, ‘
Beyonce
’]
guys = [‘Stone’, ‘Rock’, ‘Lance’]Slide12
Attributes and Methods
Attribute
: a “field” in an object.
A.k.a. a characteristic, property, or an instance variable.
a “noun”: something an object “has”.
Method
:
Operation/function
you ask an object to do to itself.
it is a verb
.Slide13
Question
Which of the following is not a good attribute name of a Car?
numWheels
accelerate
color
year
manufacturerSlide14
Q2
Which of the following is not a good method name of a Person class?
hairColor
speak
climbStairs
walk
jumpSlide15
Syntax to do all this
Need to define the class…
name
attributes of an object
methods that can be called to operate on the object.Slide16
Syntax of class definition
class Student: # use Capital Letter
“””A class that represents a Student.”””
def
__
init
__(self, name, year, grades):
“””Constructor to make a new students
instance (object).”””
self.myName
= name
self.myYear
= year
self.myGrades
= grades
student1 = Student( “Dan”, 4, [80, 82, 6] )
First, define how to create an instance of a Student class.
Assign given parameter values to attributes in new object.
self is the new instance (object) being created and initializedSlide17
self
Note that there is code “on the inside” – code inside the class definition.
Code in
__
init
__
,
getName
()
, etc.
This code refers to the object as
self
.
Then, there is code on the outside:
stud1 = Student( “Dan”, 4, [100, 90, 80] )
This code refers to the object as
stud1
.Slide18
Differences from using a list
fields have clear names!
self.name
is the student’s name, instead of
stud[0]
.
fields are not stored in any order: just “owned” by the object.Slide19
cs104Student.click()
How many syntax errors are there in this code?:
class Car
def
_
init
_(make, model, year):
self.myMake
= make
self.myModel
= model
myYear
= yearSlide20
cs104Student.clickAgain()
Given this class definition:
class Car:
def
__
init
__(self, make, model, year):
self.myMake
= make
self.myModel
= model
self.myYear
= year
which is legal code to make a new Car instance?
aCar
= Car.__
init
__(self, “Honda”, “Odyssey”, 2001)
aCar
= Car.__
init
__("Honda", "Odyssey", 2001
)aCar = Car("Honda", "Odyssey", 2001
)aCar = Car(self, "Honda", "Odyssey", 2001)
Car(aCar, "Honda", "Odyssey", 2001)Slide21
getters/
accessors
and
setters/
mutators
First methods typically written are to allow code that uses the class to access/change the attributes:
If you define attribute
xyz
, you create:
def
getXyz
(self):
“”“return the xyz value for this object”””
return
self.xyz
def
setXyz
(self,
newXyz
):
“””set the attribute xyz to the new value”””
self.xyz
=
newXyzSlide22
Example
class Student:
def
__
init
__(self, name, year, grades):
self.myName
= name
self.myYear
= year
def
getName
(self):
return
self.myName
def
setName
(self,
newName
):
self.myName
= newName
def getYear(self): return
self.myYear
def
setYear
(self,
newYear
):
self.myYear
= newYear# Create a studentstudent1 = Student( “Angelina”, 10, [] )Slide23
Example Continued
# Old Code:
name
=
getName
(student1)
year
=
getYear
(student2)
if
getLowestGrade
(student1) >
getLowestGrade
(student2):
print “Good job, student!
”
# Now:
name
= student1.getName(
)
year = student2.getYear()
if student1.getLowestGrade() > student2.getLowestGrade():
print
“Good
job, student!”
self “inside” the codeSlide24
If there is time…
List 8 properties you might want to store about a Car. List the type of each property.
Write the first line of the class definition, and the constructor. The constructor initializes attributes to given values.
Write a getter method for each of 2 attributes.
Write a setter method for 2 attributes that can be changed.