View
226
Download
0
Category
Preview:
Citation preview
Classes
COMPSCI 105 SS 2015Principles of Computer Science
COMPSCI 1052
Exercise Work on PreLab01 What is the output of the following code
fragment?
Lecture03
x = ['a', 'b', 'c']y = x z = ['a', 'b', 'c']print (x is y)print (x == y)print (x is z)print (x == z)
COMPSCI 1053
Classes Python has a number of classes built-in
lists, dictionaries, sets, int, float, boolean, strings
We can define our own classes creates a new type of object in Python
Classes consist of: state variables (sometimes called instance variables) methods (functions that are linked to a particular
instance of the class)
class name_of_the_class: definition of the class goes here
Lecture03
COMPSCI 1054
Example An example:
Instantiating Classes A class is instantiated by calling the class object:
class foo: a, b, c = 0, "bar", (1,2)
i = foo()print (i.a)print (i.b)print (i.c)
0bar(1, 2)
Lecture03
Example01.py
COMPSCI 1055
The simplest class possible Note: “Pass” is a statement that does nothing
It is often used as a placeholder when developing codeclass Point: pass
>>> p = Point()>>> p<__main__.Point object at 0x02702570>>>> p.x = 2>>> p.y = 4>>> p.x2>>> p.y4
Lecture03
Example02.py
COMPSCI 1056
Saving the class Classes are designed to help build modular code
Can be defined within a module that also contains application code
Multiple classes can be defined in the same file In this course, we will typically store each class in
their own module To use the class in another module, you will need to
import the moduleclass Point: ...
Saved in a file called Geometry.py
from Geometry import Point
p = Point(5,7)
Use the class like this
px: 5
y: 7
The object
in memor
y
Lecture03
Geometry.py
COMPSCI 1057
Setting the initial state of the object We want to define the Point class so we can write
code that sets the initial values of some variables
First, we need to define a special method of the Point class called a constructor The constructor is called whenever you create an
object of the Point class.
from Geometry import Point
p = Point(5, 7)
Lecture03
COMPSCI 1058
Constructors Each class should contain a constructor method
Name of the method is __init__ The method always has at least one parameter, called
self Self is a reference to the object that we are creating The constructor can have other parametersclass Point:
def __init__(self, loc_x, loc_y): self.x = loc_x self.y = loc_y
from Geometry import Point
p = Point(5, 7)print(p.x)print(p.y)
Lecture03
Saved in a file called Geometry.py
COMPSCI 1059
Adding functionality Defining more methods
A method to shift a point by a given amount in horizontal and vertical directions
Note: the method is named normally, but has the additional parameter (self) as the first parameter All methods that are called on an instance of an object need the
self parameter
class Point: def __init__(self, loc_x, loc_y): self.x = loc_x self.y = loc_y
def translate(self, dx, dy): self.x += dx self.y += dy
Lecture03
COMPSCI 10510
Using the Point class Methods are defined to accept self as the first
parameter
We call the method using: object_name.method(params)
class Point: def __init__(self, loc_x, loc_y): self.x = loc_x self.y = loc_y
def translate(self, dx, dy): self.x += dx self.y += dy
from Geometry import Pointp = Point(0,0)p.translate(10,5)
Lecture03
COMPSCI 10511
Exercise 1 Define a class that will be used to represent a
square with a given side length. Your class should include a constructor that will allow
the square to be used as follows:
Add a method to the class to calculate the perimeter of the square. The following code shows how the method may be used.
from Geometry import Squareside = 10s = Square(side)
print (s.perimeter())
Lecture03
40
COMPSCI 10512
Write a class to represent fractions in Python create a fraction add subtract multiply divide text representation
Example: Fractions
½numeratordenominator
Lecture03
COMPSCI 10513
Model of objects in memory
methods
state
num:
den:
7
8
methods
state
num:
den:
3
4
methods
state
num:
den:
1
2
xy
z
from Fraction import Fraction
x = Fraction(1,2)y = Fraction(3,4)z = Fraction(7,8)
Lecture03
Example03.py
COMPSCI 10514
All classes must have a constructor The constructor for a Fraction should store the
numerator and the denominator
Constructor
class Fraction: def __init__(self, top, bottom): self.num = top #numerator self.den = bottom #denominator
Lecture03
COMPSCI 10515
So far, we can create a Fraction
We can access the state variables directly Although not generally good practice to do so
What else can we do with Fractions? Nothing yet. We need to write the functions first!
Using the Fraction class
>>> x.num3>>> x.den4
>>> x = Fraction(3, 4)
Lecture03
Lecture 04
COMPSCI 10516
Overriding default behaviour All classes get a number of methods provided by
default Since default behaviour is not very useful, we should
write our own versions of those methods __repr__ __str__
Lecture03
COMPSCI 10517
Often we want to use a string that combines literal text and information from variables Example:
We can use string formatting to perform this task Use curly braces within the string to signify a variable
to be replaced
We can put the argument position in the curly braces
Aside: Use of string formatting syntax
name = 'Andrew'greeting = 'Hello ' + name + '. How are you?'
my_name = 'Andrew'greeting = 'Hello {name}. How are you?'.format(name=my_name)
first = 'Andrew'second = 'Luxton-Reilly'greeting = 'Hello {0} {1}'.format(first, second)
Lecture03
COMPSCI 10518
The __repr__ method produces an string that unambiguously describes the object All classes should have a __repr__ function
implemented Ideally, the representation could be used to create the
object For example, a fraction created using Fraction(2, 3) should
have a __repr__ method that returned 'Fraction(2, 3)'
Using the object
__repr__
class Fraction:def __init__(self, top, bottom): self.num = top
self.den = bottom def __repr__(self): return 'Fraction({0}, {1})'.format(self.num, self.den)
>>> x = Fraction(2, 3)>>> x
Fraction(2, 3)
Lecture03
COMPSCI 10519
Without the __repr__ method
>>> x = Fraction(2, 3)>>> x
class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom
<__main__.Fraction object at 0x02762290>)
Lecture03
COMPSCI 10520
The __str__ method returns a string representing the object By default, it calls the __repr__ method The __str__ method should focus on being human
readable We should implement a version with a natural
representation:
After we have implemented the method, we can use standard Python
__str__
def __str__(self): return str(self.num) + '/' + str(self.den)
>>> x = Fraction(3, 4)>>> print(x)3/4
Lecture03
COMPSCI 10521
Without the __str__ method
>>> x = Fraction(2, 3)>>> print(x)
class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom
<__main__.Fraction object at 0x02714290>
Lecture03
COMPSCI 10522
Exercise 2 Write the __repr__ method for the Square class
created earlier.
Would it be useful to implement a __str__ method?
What would you choose to produce as output from a __str__ method?
Lecture03
Recommended