Download presentation
Presentation is loading. Please wait.
Published byIsabella Blankenship Modified over 9 years ago
1
Classes COMPSCI 105 SS 2015 Principles of Computer Science
2
Exercise Work on PreLab01 What is the output of the following code fragment? Lecture03COMPSCI 1052 x = ['a', 'b', 'c'] y = x z = ['a', 'b', 'c'] print (x is y) print (x == y) print (x is z) print (x == z) x = ['a', 'b', 'c'] y = x z = ['a', 'b', 'c'] print (x is y) print (x == y) print (x is z) print (x == z)
3
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 class name_of_the_class: definition of the class goes here Lecture03COMPSCI 1053
4
Example An example: Instantiating Classes A class is instantiated by calling the class object: class foo: a, b, c = 0, "bar", (1,2) class foo: a, b, c = 0, "bar", (1,2) i = foo() print (i.a) print (i.b) print (i.c) i = foo() print (i.a) print (i.b) print (i.c) 0 bar (1, 2) 0 bar (1, 2) Lecture03COMPSCI 1054 Example01.py
5
The simplest class possible Note: “Pass” is a statement that does nothing It is often used as a placeholder when developing code class Point: pass class Point: pass >>> p = Point() >>> p >>> p.x = 2 >>> p.y = 4 >>> p.x 2 >>> p.y 4 >>> p = Point() >>> p >>> p.x = 2 >>> p.y = 4 >>> p.x 2 >>> p.y 4 Lecture03COMPSCI 1055 Example02.py
6
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 module class Point:... class Point:... Saved in a file called Geometry.py from Geometry import Point p = Point(5,7) from Geometry import Point p = Point(5,7) Use the class like this p x:5 y:7 The object in memory Lecture03COMPSCI 1056 Geometry.py
7
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) from Geometry import Point p = Point(5, 7) Lecture03COMPSCI 1057
8
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 parameters class Point: def __init__(self, loc_x, loc_y): self.x = loc_x self.y = loc_y class 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) from Geometry import Point p = Point(5, 7) print(p.x) print(p.y) Lecture03COMPSCI 1058 Saved in a file called Geometry.py
9
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 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 Lecture03COMPSCI 1059
10
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 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 Point p = Point(0,0) p.translate(10,5) from Geometry import Point p = Point(0,0) p.translate(10,5) Lecture03COMPSCI 10510
11
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 Square side = 10 s = Square(side) from Geometry import Square side = 10 s = Square(side) print (s.perimeter()) Lecture03COMPSCI 10511 40
12
Write a class to represent fractions in Python create a fraction add subtract multiply divide text representation Example: Fractions ½ numerator denominator Lecture03COMPSCI 10512
13
Model of objects in memory methods state num: den: 7 8 methods state num: den: 3 4 methods state num: den: 1 2 x y z from Fraction import Fraction x = Fraction(1,2) y = Fraction(3,4) z = Fraction(7,8) from Fraction import Fraction x = Fraction(1,2) y = Fraction(3,4) z = Fraction(7,8) Lecture03COMPSCI 10513 Example03.py
14
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 class Fraction: def __init__(self, top, bottom): self.num = top #numerator self.den = bottom #denominator Lecture03COMPSCI 10514
15
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.num 3 >>> x.den 4 >>> x.num 3 >>> x.den 4 >>> x = Fraction(3, 4) Lecture03COMPSCI 10515 Lecture 04
16
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__ Lecture03COMPSCI 10516
17
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?' name = 'Andrew' greeting = 'Hello ' + name + '. How are you?' my_name = 'Andrew' greeting = 'Hello {name}. How are you?'.format(name=my_name) 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) first = 'Andrew' second = 'Luxton-Reilly' greeting = 'Hello {0} {1}'.format(first, second) Lecture03COMPSCI 10517
18
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) 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 >>> x = Fraction(2, 3) >>> x Fraction(2, 3) Lecture03COMPSCI 10518
19
Without the __repr__ method >>> x = Fraction(2, 3) >>> x >>> x = Fraction(2, 3) >>> x class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom ) Lecture03COMPSCI 10519
20
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) def __str__(self): return str(self.num) + '/' + str(self.den) >>> x = Fraction(3, 4) >>> print(x) 3/4 >>> x = Fraction(3, 4) >>> print(x) 3/4 Lecture03COMPSCI 10520
21
Without the __str__ method >>> x = Fraction(2, 3) >>> print(x) >>> x = Fraction(2, 3) >>> print(x) class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom class Fraction: def __init__(self, top, bottom): self.num = top self.den = bottom Lecture03COMPSCI 10521
22
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? Lecture03COMPSCI 10522
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.