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)

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Python Objects and Classes
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
Class Hierarchy (Inheritance)
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions (Large parts of these copied from Ed Schonberg’s slides)
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
Object Oriented Programming
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
General Programming Introduction to Computing Science and Programming I.
Object-oriented Programming (review + a few new tidbits) "Python Programming for the Absolute Beginner, 3 rd ed." Chapters 8 & 9 Python 3.2 reference.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Introduction. 2COMPSCI Computer Science Fundamentals.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
VB.Net - Exceptions Copyright © Martin Schray
CSC 508 – Theory of Programming Languages, Spring, 2009 Week 3: Data Abstraction and Object Orientation.
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
Classes 1 COMPSCI 105 S Principles of Computer Science.
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
Before starting OOP… Today: Review Useful tips and concepts (based on CS 11 Python track, CALTECH)
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
Inheritance and Access Control CS 162 (Summer 2009)
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
CS1101 Group1 Discussion 6 Lek Hsiang Hui comp.nus.edu.sg
Lecture 4 Python Basics Part 3.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exceptions and Handling
Comp1004: Inheritance II Polymorphism. Coming up Inheritance Reminder Overriding methods – Overriding and substitution Dynamic Binding Polymorphism –
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Introduction to Computing Science and Programming I
George Mason University
COMPSCI 107 Computer Science Fundamentals
Why exception handling in C++?
Lecture VI Objects The OOP Concept Defining Classes Methods
Creating and Deleting Instances Access to Attributes and Methods
Python Classes By Craig Pennell.
Java Programming Language
Python’s Errors and Exceptions
Exceptions.
Exceptions 1 CMSC 202.
Problems Debugging is fine and dandy, but remember we divided problems into compile-time problems and runtime problems? Debugging only copes with the former.
By Ryan Christen Errors and Exceptions.
Access Control Damian Gordon.
CMSC 202 Lesson 20 Exceptions 1.
Presentation transcript:

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) that operate on it

OOP terminology class -- a template for building objects instance -- an object created from the template (an instance of the class) method -- a function that is part of the object and acts on instances directly constructor -- special "method" that creates new instances

Defining a class class Thingy: """This class stores an arbitrary object.""" def __init__(self, value): """Initialize a Thingy.""" self.value = value def showme(self): """Print this object to stdout.""" print "value = %s" % self.value constructor method

Using a class (1) t = Thingy(10) # calls __init__ method t.showme() # prints "value = 10" t is an instance of class Thingy showme is a method of class Thingy __init__ is the constructor method of class Thingy when a Thingy is created, the __init__ method is called Methods starting and ending with __ are "special" methods

Using a class (2) print t.value # prints "10" value is a field of class Thingy t.value = 20 # change the field value print t.value # prints "20"

More fun stuff Can write showme a different way: def __repr__(self): return str(self.value) Now can do: print t # prints "10" print "thingy: %s" % t # prints "thingy: 10" __repr__ converts object to string

"Special" methods All start and end with __ (two underscores) Most are used to emulate functionality of built-in types in user-defined classes e.g. operator overloading __add__, __sub__, __mult__,... see python docs for more information

Exception handling What do we do when something goes wrong in code? exit program (too drastic) return an integer error code (clutters code) Exception handling is a cleaner way to deal with this Errors "raise" an exception Other code can "catch" an exception and deal with it

try/raise/except (1) try: a = 1 / 0 # this raises ZeroDivisionError except ZeroDivisionError: # catch and handle the exception print "divide by zero" a = -1 # lame!

try/raise/except (2) try: a = 1 / 0 # this raises ZeroDivisionError except: # no exception specified # catches ANY exception print "something bad happened" # Don’t do this!

try/raise/except (3) try: a = 1 / 0 # this raises ZeroDivisionError except: # no exception specified # Reraise original exception: raise # This is even worse!

Backtraces Uncaught exceptions give rise to a stack backtrace: # python bogus.py Traceback (most recent call last): file "bogus.py", line 5, in ? foo() file "bogus.py", line 2, in foo a = 1 / 0 ZeroDivisionError: integer division or modulo by zero Backtrace is better than catch-all exception handler

Exceptions are classes class SomeException: def __init__(self, value=None): self.value = value def __repr__(self): return `self.value` The expression `self.value` is the same as str(value) i.e. converts object to string

Raising exceptions (1) def some_function(): if something_bad_happens(): # SomeException leaves function raise SomeException("bad!") else: # do the normal thing

Raising exceptions (2) def some_other_function(): try: some_function() except SomeException, e: # e gets the exception that was caught print e.value

Raising exceptions (3) # This is silly: try: raise SomeException("bad!") except SomeException, e: print e # prints "bad!"

Random numbers (1) To use random numbers, import the random module; some useful functions include: random.choice(seq) chooses a random element from a sequence seq (usually a list) random.shuffle(seq) randomizes the order of elements in a sequence seq (usually a list) random.sample(seq, k) chooses k random elements from seq

Random numbers (2) To use random numbers, import the random module; some useful functions include: random.randrange(start, stop) chooses a random element from the range [ start, stop ] (not including the endpoint) random.randint(start, stop) chooses a random element from the range [ start, stop ] (including the endpoint) random.random() returns a random float in the range ( 0, 1 )

Summing up Use classes where possible Use exceptions to deal with error situations Use docstrings for documentation Next week: more OOP (inheritance)

More on OOP -- inheritance Often want to create a class which is a specialization of a previously-existing class Don't want to redefine the entire class from scratch Just want to add a few new methods and fields To do this, the new class can inherit from another class; this is called inheritance The class being inherited from is called the parent class, base class, or superclass The class inheriting is called the child class, derived class, or subclass

Inheritance (2) Inheritance: class DerivedClass(BaseClass):... Or: class DerivedClass(mod.BaseClass): #... if BaseClass is defined in another module (" mod ")

Inheritance (3) Name resolution: foo = Foo() # instance of class Foo foo.bar() If bar method not in class Foo parent class of Foo searched etc. until bar found or top reached AttributeError raised if not found Same deal with fields ( foo.x )

Inheritance (4) Constructors: Calling __init__ method on subclass doesn't automatically call superclass constructor! Can call superclass constructor explicitly if necessary

Inheritance (5) class base: def __init__(self, x): self.x = x class derive (base): def __init__(self, y): base.__init__(self, y) self.y = y

Inheritance example (1) class Animal: def __init__(self, weight): self.weight = weight def eat(self): print "I am eating!" def __repr__(self): return "Animal; weight = %d" % \ self.weight

Inheritance example (2) >>> a = Animal(100) >>> a.eat() I am eating! >>> a.weight 100 >>> a.fly() AttributeError: Animal instance has no attribute 'fly'

Inheritance example (3) class Bird(Animal): def fly(self): print "I am flying!" b = Bird(100) # Animal's __init__() method b.eat() I am eating! b.fly() I am flying!

Multiple inheritance (1) Multiple inheritance: class DerivedClassName(Base1, Base2, Base3):.. Resolution rule for repeated attributes: Left-to-right, depth first search sorta... Actual rules are slightly more complex Don't depend on this if at all possible!

Multiple inheritance (2) Detailed rules: Usually used with "mixin" classes Combining two completely independent classes Ideally no fields or methods shared Conflicts then do not arise

Mixin example class DNASequence: # __init__ etc. def getBaseCounts(self): #... # other DNA-specific methods class DBStorable: # __init__ etc. # methods for storing into database class StorableDNASequence(DNASequence, \ DBStorable): # Override methods as needed # No common fields/methods in superclasses

Private fields Private fields of objects at least two leading underscores at most one trailing underscore e.g. __spam __spam  _ __spam is current class name Weak form of privacy protection