Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

Python Programming Chapter 13: Classes and Functions Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Python Mini-Course University of Oklahoma Department of Psychology
Python Objects and Classes
Python Mini-Course University of Oklahoma Department of Psychology Day 1 – Lesson 4 Beginning Functions 4/5/09 Python Mini-Course: Day 1 - Lesson 4 1.
This Week More Types boolean string Modules print statement Writing programs if statement Type boolean.
Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 8 Fruitful Functions 05/02/09 Python Mini-Course: Day 2 - Lesson 8 1.
2/7/2008. >>> Overview * boolean * while * random * tuples.
Order of operators: x ** y x * y, x / y, x // y, x % y x + y, x - y
Python Mini-Course University of Oklahoma Department of Psychology Lesson 26 Classes and Objects 6/16/09 Python Mini-Course: Lesson 26 1.
Def f(n): if (n == 0): return else: print(“*”) return f(n-1) f(3)
Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 15 Tuples 5/02/09 Python Mini-Course: Day 4 – Lesson 15 1.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Main task -write me a program
Testing a program Remove syntax and link errors: Look at compiler comments where errors occurred and check program around these lines Run time errors:
C++ fundamentals.
Python quick start guide
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
Exceptions COMPSCI 105 S Principles of Computer Science.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Classes 3 COMPSCI 105 S Principles of Computer Science.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
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.
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 9 Iteration: Recursion 5/02/09 Python Mini-Course: Day 3 - Lesson 9 1.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #005 (April somthin, 2015)
Hey, Ferb, I know what we’re gonna do today! Aims: Use formatted printing. Use the “while” loop. Understand functions. Objectives: All: Understand and.
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 5 Function Interfaces 4/18/09 Python Mini-Course: Day 2 - Lesson 5 1.
Functions Chapter 4 Python for Informatics: Exploring Information
Chapter 4 Loops Write code that prints out the numbers Very often, we want to repeat a (group of) statement(s). In C++, we have 3 major ways of.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Python Mini-Course University of Oklahoma Department of Psychology Day 2 – Lesson 7 Conditionals and Loops 4/18/09 Python Mini-Course: Day 2 - Lesson 7.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
Object Oriented Programing (OOP)
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Python Let’s get started!.
Basic Concepts of OOP.  Object-Oriented Programming (OOP) is a type of programming added to php5 that makes building complex, modular and reusable web.
The Python Language Petr Přikryl Part IIb Socrates IP, 15th June 2004 TU of Brno, FIT, Czech Republic.
Debugging and Printing George Mason University. Today’s topics Review of Chapter 3: Printing and Debugging Go over examples and questions debugging in.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 27 Classes and Functions 6/17/09 Python Mini-Course: Lesson 27 1.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Exceptions and Handling
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
Today… Python Keywords. Iteration (or “Loops”!) Winter 2016CISC101 - Prof. McLeod1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Fundamentals of Python: First Programs
George Mason University
Python Let’s get started!.
Introduction to Python
Agenda Warmup Finish 2.4 Assignments
IFS410: Advanced Analysis and Design
Programming with Microsoft Visual Basic 2008 Fourth Edition
I210 review.
What does this do? def revList(L): if len(L) < = 1: return L x = L[0] LR = revList(L[1:]) return LR + x.
COP 3330 Object-oriented Programming in C++
CISC101 Reminders All assignments are now posted.
Object Oriented Programming in A Level
COMPUTER PROGRAMMING SKILLS
By Ryan Christen Errors and Exceptions.
C++ Programming CLASS This pointer Static Class Friend Class
Data Types Every variable has a given data type. The most common data types are: String - Text made up of numbers, letters and characters. Integer - Whole.
Unit Testing.
Presentation transcript:

Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1

Lesson objectives 1. Create methods inside class definitions 2. Call methods using function syntax and method syntax 3. Create custom __init__ and __str__ methods 4. Use operator overloading 6/17/09 Python Mini-Course: Lesson 28 2

Encapsulation Data and behaviors are packaged together The object only reveals the interfaces needed to interact with it Internal data and behaviors can remain hidden 6/17/09 Python Mini-Course: Lesson 28 3

Encapsulating the Time class Instead of using functions, we want to use methods Move the functions inside the class definition 6/17/09 Python Mini-Course: Lesson 28 4

The print_time() method class Time(object): … def print_time(self): """ Print the time in hour:minute:second format. """ print '%02d:%02d:%02d' % \ (self.hour, self.minute, self.second) 6/17/09 Python Mini-Course: Lesson 28 5

Calling a method Using function syntax t1 = Time(2,35) Time.print_time(t1) Using method syntax t1.print_time() 6/17/09 Python Mini-Course: Lesson 28 6

Converting the other functions to methods The valid_time method The increment method The add_time method 6/17/09 Python Mini-Course: Lesson 28 7

The valid_time method class Time(object):... def valid_time(self): validity = True # All values must be at least zero if self.hour < 0 or self.minute < 0 \ or self.second < 0: validity = False # Minute and second must be base 60 if self.minute >= 60 or self.second >= 60: validity = False return validity 6/17/09 Python Mini-Course: Lesson 28 8

The increment method class Time(object):... def increment(self, t2): # Check the input arguments if type(t2) != Time: raise AttributeError, \ 'invalid argument passed to Time.increment()' if not t2.valid_time(): raise ValueError, \ 'invalid Time object passed to Time.increment()' # Add the times self.hour += t2.hour self.minute += t2.minute self.second += t2.second 6/17/09 Python Mini-Course: Lesson 28 9

The add_time method class Time(object):... def add_time(self, t2): # Add the times new_time = Time() new_time.hour = self.hour + t2.hour new_time.minute = self.minute + t2.minute new_time.second = self.second + t2.second # Return the sum return new_time 6/17/09 Python Mini-Course: Lesson 28 10

Using the Time class t1 = Time(0,0,30) t2 = Time(1,0,45) t1.increment(t2) t1.print_time() t3 = t1.add_time(t2) t3.print_time() t4 = Time.add_time(t1, t2) t4.print_time() 6/17/09 Python Mini-Course: Lesson 28 11

Improving the Time class Problems: 1. Formatting 1. Minutes and seconds should always be less than Printing is awkward 3. Adding times is awkward Solutions: see time_oop1.py 6/17/09 Python Mini-Course: Lesson 28 12

Keeping the right format class Time(object):... def adjust_base_60(self): # Increment minutes as necessary and adjust seconds self.minute += self.second // 60 self.second = self.second % 60 # Increment hours as necessary and adjust minutes self.hour += self.minute // 60 self.minute = self.minute % 60 6/17/09 Python Mini-Course: Lesson 28 13

Controlling access to attributes class Time(object):... def set_time(self, hour=0, minute=0, second=0): self.hour = hour self.minute = minute self.second = second self.adjust_base_60() 6/17/09 Python Mini-Course: Lesson 28 14

The __str__ method class Time(object): … def __str__(self): """ Return the time in hour:minute:second format. """ return '%02d:%02d:%02d' % \ (self.hour, self.minute, self.second) 6/17/09 Python Mini-Course: Lesson 28 15

The __str__ method The __str__ method is a special method that is called by the str() and print commands t1 = Time(2,45) str(t1) print t1 6/17/09 Python Mini-Course: Lesson 28 16

Why does this work? In Python, the most basic class, the object class, defines the __str__ method Time is a sub-class of the object class, and it inherits this behavior By defining our own __str__ method we override the base class method This is polymorphism 6/17/09 Python Mini-Course: Lesson 28 17

Operator overloading We can also define how a class responds to standard operators such as +, -, etc. This is called operator overloading 6/17/09 Python Mini-Course: Lesson 28 18

The __add__ method class Time(object):... def __add__(self, other): return self.add_time(other) def add_time(self, t2): new_time = Time() new_time.hour = self.hour + t2.hour new_time.minute = self.minute + t2.minute new_time.second = self.second + t2.second new_time.adjust_base_60() return new_time 6/17/09 Python Mini-Course: Lesson 28 19

Using the __add__ method t1 = Time(0,0,30) t2 = Time(1,0,45) t3 = t1 + t2 print t3 print t1 + t2 6/17/09 Python Mini-Course: Lesson 28 20

Type-based dispatch Allow us to use different types of arguments for the same method (or function) 6/17/09 Python Mini-Course: Lesson 28 21

class Time(object):... def increment(self, t2): # Check the input arguments if type(t2) == Time: # Add the times self.hour += t2.hour self.minute += t2.minute self.second += t2.second elif type(t2) == int: # Increment the seconds self.second += t2 else: raise AttributeError, \ 'invalid argument passed to Time.increment()' self.adjust_base_60() 6/17/09 Python Mini-Course: Lesson 28 22

For more practice, try Think Python. Chap 17 Exercise 17.3, page 165 Exercise 17.4, page 166 Exercise 17.5, page 167 Exercise 17.6, page 169 (debugging exercise) 6/17/09 Python Mini-Course: Lesson 28 23

Assignment Think Python. Chap 18 Read text Type in and run code as you go (save as poker.py) Do Exercises 18.2 and 18.3 in text 6/17/09 Python Mini-Course: Lesson 28 24