Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein Classes and Objects Object Oriented Programming.

Slides:



Advertisements
Similar presentations
Final and Abstract Classes
Advertisements

1 Inheritance Classes and Subclasses Or Extending a Class.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
1 Linked Lists III Template Chapter 3. 2 Objectives You will be able to: Write a generic list class as a C++ template. Use the template in a test program.
Access Lesson 13 Programming in Access Microsoft Office 2010 Advanced Cable / Morrison 1.
1 User-Defined Classes The String class is a pre-defined class that is provided by the Java Designer. Sometimes programmers would like to create their.
Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Python Objects and Classes
Lilian Blot CORE ELEMENTS SELECTION & FUNCTIONS Lecture 3 Autumn 2014 TPOP 1.
CHAPTER 11 FILE INPUT & OUTPUT Introduction to Computer Science Using Ruby (c) 2012 Ophir Frieder et al.
Lecture 04 – Classes.  Python has a number of classes built-in  lists, dictionaries, sets, int, float, boolean, strings  We can define our own classes.
Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein Classes and Objects Object Oriented Programming.
CSC241 Object-Oriented Programming (OOP) Lecture No. 9.
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein Classes and Objects Object Oriented Programming.
Lecture Roger Sutton 21: Revision 1.
VBA Modules, Functions, Variables, and Constants
CS 106 Introduction to Computer Science I 03 / 23 / 2007 Instructor: Michael Eckmann.
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
Nextgen Bank Reconciliation Resource Bank Reconciliation Menu Financial Management Bank Reconciliation –Import Bank Statements –Reconcile Bank Accounts.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
Object Oriented Programming Elhanan Borenstein Lecture #4.
C++ Programming for Graphics Lecture 5 References, New, Arrays and Destructors.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
CSE 131 Computer Science 1 Module 1: (basics of Java)
Working With Objects Tonga Institute of Higher Education.
Object Oriented Programming Elhanan Borenstein Lecture #3 copyrights © Elhanan Borenstein.
Object Oriented Programming Elhanan Borenstein Lecture #10 copyrights © Elhanan Borenstein.
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏ Sec 9-7 Web Design.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Working With Objects Tonga Institute of Higher Education.
COPYRIGHT 2010: Dr. David Scanlan, CSUS OBJECTIVES: How to write classes How to create an object from a class using the "New" keyword. How to communicate.
Object Oriented Programing (OOP)
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
1 CS161 Introduction to Computer Science Topic #16.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
Data Manipulation Variables, Data Types & Math. Aug Variables A variable is a name (identifier) that points to a value. They are useful to store.
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
What is an object?. What Makes an Object? An object has identity (it acts as a single whole). Every object has a name that identifies what it is. Ex.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
CMSC 202 Lesson 9 Classes III. Warmup Using the following part of a class, implement the Sharpen() method, it removes 1 from the length: class Pencil.
CSC 1010 Programming for All Lecture 5 Functions Some material based on material from Marty Stepp, Instructor, University of Washington.
Whatcha doin'? Aims: To start using Python. To understand loops.
CS-104 Final Exam Review Victor Norman.
Functions CIS 40 – Introduction to Programming in Python
Arrays in C.
CSC 113 Tutorial QUIZ I.
IFS410: Advanced Analysis and Design
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Learning Objectives Classes Constructors Principles of OOP
Variables, Data Types & Math
Variables, Data Types & Math
Variables, Data Types & Math
Chapter 9 Introduction To Classes
CISC101 Reminders Assignment 3 due today.
Classes and Objects Object Creation
CMSC 202 Constructors Version 9/10.
Presentation transcript:

Genome 559: Introduction to Statistical and Computational Genomics Elhanan Borenstein Classes and Objects Object Oriented Programming

A quick review  A class defines variables’ types: 1.What kind of data is stored (members) 2.What are the available functions (methods)  An object is an instance of a class:  string is a class; my_str = “AGGCGT” creates an object of the class string, called my_str.  Why classes:  Bundle together data and operations on data  Allow special operations appropriate to data  Allow context-specific meaning for common operations  Help organize your code and facilitates modular design  The human factor

A Date class example class Date: day = 0 month = "None" def printUS(self): print self.month, "/", self.day def printUK(self): print self.day, ".", self.month mydate = Date() mydate.day = 15 mydate.month= "Jan" mydate.printUS() Jan / 15 mydate.printUK() 15. Jan class functions (methods) Access (call) functions of this Date object Where did the argument go? Define the class Date Create and initialize class members Special name “self” refers to the current object (no matter what the caller named it). Access data members of this Date object

Class declarations and usage - Summary  The class statement defines a new class  Remember the colon and indentation  You can include data members (variables) and functions as part of your class. These will be accessed using the dot (.) notation (e.g., mydate.day)  The special name self means the current object  self. refers to instance variables of the class  self is automatically passed to each method as a 1 st argument class : …

We’re getting there …  What do we have so far:  Date data are bundled together (sort of …)  Copying the whole thing at once is very handy  Printing is easy and provided as a service by the class  Still on our wish-list:  We still have to handle printing the various details  Error checking - e.g., possible to forget to fill in the month  No Date operations (add, subtract, etc.)

An even better Date class class Date: def __init__(self, day, month): self.day = day self.month = month def printUS(self): print self.mon, "/", self.day def printUK(self): print self.day, ".", self.mon mydate = Date(15,"Jan") mydate.printUS() Jan / 15 mydate2 = Date(22,“Nov") mydate2.printUK() 22. Nov Note the magical first arguments: __init__ defined w/ 3 args; called w/ 2; printUS defined w/ 1 arg; called w/ 0. mydate is passed in both cases as 1 st arg, so each function knows on which object it is to act Special function “_ _init_ _” is called whenever a Date object instance is created. (class constructor) It makes sure the object is properly initialized Now, when “constructing” a new Date object, the caller MUST supply required data

Dreams do come true (sometimes)  What do we have so far:  Date data are bundled together (sort of …)  Copying the whole thing at once is very handy  Printing is easy and provided as a service by the class  User MUST provide data when generating a new Date object  Still on our wish-list:  We still have to handle printing the various details  Error checking - e.g., possible to forget to fill in the month  No Date operations (add, subtract, etc.)

Second thoughts …  True, we now have a “print” function, but can we somehow make printing more intuitive?  Specifically, why is “print” fine for numbers, strings, etc. >>> my_str = “hello” >>> my_num = 5 >>> print my_str, my_num “hello” 5 but funky for class instances? >>> print mydate  Yes, mydate.printUS() works, but seems clunky …

A better way to print objects  Actually, “print” doesn’t have special knowledge of how to print numbers, lists, etc.  It just knows how to print strings, and relies on each class to have a __str__() method that returns a string representing the object.  You can write your own, tailored __str__() method to give prettier/more useful results

A super Date class class Date: def __init__(self, day, month): self.day = day self.month = month def __str__(self) : day_str = ‘%s’ % self.day mon_str = ‘%s’ % self.month return mon_str + “-” + day_str birthday = Date(3,”Sep”) print “It’s ”, birthday, “. Happy Birthday!” It’s Sep-3. Happy Birthday!

Advanced topic: Allowing the plus sign  Similarly, how come “+” works (but differently) for numbers and strings but not for dates?  Yes, we could write a function addDays(n) : party = birthday.addDays(4)  But … would be much more natural (and way cooler) to be able to write: party = birthday + 4  Can we do it?

Operator overloading  Yes! Again, ‘+’ isn’t as smart as you thought; it calls class-specific “add” methods _ _add_ _() to do the real work.  We can make new classes, like Date, behave like built- in ones  Common operator overloading methods:  _ _init_ _ # object creation  _ _add_ _ # addition (+)  _ _mul_ _ # multiplication (*)  _ _sub_ _ # subtraction (-)  _ _lt_ _ # less than (<)  _ _str_ _ # printing  _ _call_ _ # function calls  Many more...

TIP OF THE DAY Code like a pro …  Code running ≠ code is correct or bug-free  Be much more concerned about the bugs you don’t see than the ones you do!!  Especially true in bioinformatics, high-throughput data analysis, and simulations "Testing shows the presence, not the absence of bugs." Edsger Wybe Dijkstra 1930 –2002

Sample problem #1  Add a year data member to the Date class: 1.Allow the class constructor to get an additional argument denoting the year 2.If the year is not provided in the constructor, the class should assume it is 2011 (Hint: remember the default value option in function definition) 3.When printing in US format, print all 4 digits of the year. When printing in UK format, print only the last 2 digits. (Hint: str(x) will convert an integer X into a string) >>> mydate = Date(15,"Jan",1976) >>> mydate.printUK() 15. Jan. 76 >>> mydate = Date(21,"Feb") >>> mydate.printUS() Feb / 21 / 2010

class Date: def __init__(self, day, month, year=2011): self.day = day self.mon = month self.year = year def printUS(self): print self.mon, "/", self.day, "/", self.year def printUK(self): print self.day, ".", self.mon, ".", str(self.year)[2:] Solution #1

Sample problem #2  Change the Date class such that the month is represented as a number rather than as a string. (What did you have to do to make this change?)  Add the function addMonths(n) to the class Date. This function should add n months to the current date. Make sure to correctly handle transitions across years. (Hint: the modulo operator, %, returns the remainder in division: 8 % 3  2) >>> mydate = Date(22, 11, 1976) >>> mydate.printUK() >>> mydate.addMonths(1) >>> mydate.printUK() >>> mydate.addMonths(3) >>> mydate.printUK() >>> mydate.addMonths(25) >>> mydate.printUK()

class Date: def __init__(self, day, month, year=2011): self.day = day self.mon = month self.year = year def printUS(self): print self.mon, "/", self.day, "/", self.year def printUK(self): print self.day, ".", self.mon, ".", str(self.year)[2:] def addMonths(self, n=1): new_mon = self.mon + n self.year += (new_mon-1) / 12 self.mon = (new_mon-1) % Solution #2

Challenge Problem 1.Add the function addDays(n) to the class Date. This function should add n days to the current date. Make sure to correctly handle transitions across months AND across years (when necessary). Take into account the different number of days in each month. 2.Revise the Date class such that it will again work with the month’s name (rather than its number), while preserving the functionality of the addMonths and addDays functions.