Classes COMPSCI 105 SS 2015 Principles of Computer Science.

Slides:



Advertisements
Similar presentations
Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
Lecture 03 – Sequences of data.  At the end of this lecture, students should be able to:  Define and use functions  Import functions from modules 
Object-Oriented Programming in Python Goldwasser and Letscher Chapter 6 Defining Our Own Classes Terry Scott University of Northern Colorado 2007 Prentice.
Week 2 Classes, Objects and lists review Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise.
Program Design and Development
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
Lecture 05 – Classes.  A class provides the definition for the type of an object  Classes can store information in variables  Classes can provide methods.
Classes 2 COMPSCI 105 S Principles of Computer Science.
Unit 8 Classes and Objects; Inheritance Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except.
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Exceptions COMPSCI 105 S Principles of Computer Science.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Classes 3 COMPSCI 105 S Principles of Computer Science.
Python Programming Chapter 14: Classes and Methods Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Introduction COMPSCI 105 SS 2015 Principles of Computer Science.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Introduction. 2COMPSCI Computer Science Fundamentals.
Adding & Subtracting Whole Number and Fractions
Classes 1 COMPSCI 105 S Principles of Computer Science.
Functions. Built-in functions You’ve used several functions already >>> len("ATGGTCA")‏ 7 >>> abs(-6)‏ 6 >>> float("3.1415")‏ >>>
Adding Fractions With Like and Unlike Denominators Presented By Nathaniel Thompson.
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
Lecture 04 – Models of memory Mutable and immutable data.
JSON COMPSCI 105 SS 2015 Principles of Computer Science.
Math, Data Types. Python Math Operations OperationOperator Addition + Subtraction – Multiplication * Division (floating point) / Division (integer) //
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
JSON COMPSCI 105 S Principles of Computer Science.
Lists COMPSCI 105 S Principles of Computer Science.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Data Manipulation Variables, Data Types & Math. Aug Variables A variable is a name (identifier) that points to a value. They are useful to store.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
Equality, references and mutability COMPSCI 105 SS 2015 Principles of Computer Science.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
CSC 231: Introduction to Data Structures Python and Objects – Day 3 Dr. Curry Guinn.
Adapted from slides by Marty Stepp and Stuart Reges
Chapter VII: Arrays.
Python programming - Defining Classes
COMPSCI 107 Computer Science Fundamentals
User-Written Functions
Object Oriented Programming
Classes and Objects; Inheritance
COMPSCI 107 Computer Science Fundamentals
Introduction to Python
COMPSCI 107 Computer Science Fundamentals
Variables, Expressions, and IO
Functions CIS 40 – Introduction to Programming in Python
Adapted from slides by Marty Stepp and Stuart Reges
Week 8 Classes and Objects
Adapted from slides by Marty Stepp and Stuart Reges
Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this.
Classes, Objects and lists
Variables, Data Types & Math
Python Primer 1: Types and Operators
Variables, Data Types & Math
Variables, Data Types & Math
COMPUTER PROGRAMMING SKILLS
Terry Scott University of Northern Colorado 2007 Prentice Hall
Lecture 18 Python OOP.
A Level Computer Science Topic 6: Introducing OOP
Week 2 Classes and Objects
Presentation transcript:

Classes COMPSCI 105 SS 2015 Principles of Computer Science

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)

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

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

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

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

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

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

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

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

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

 Write a class to represent fractions in Python  create a fraction  add  subtract  multiply  divide  text representation Example: Fractions ½ numerator denominator Lecture03COMPSCI 10512

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 Example03.py

 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

 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 Lecture 04

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

 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

 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

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

 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

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

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