Python classes: new and old. New and classic classes  With Python 2.2, classes and instances come in two flavors: old and new  New classes cleaned up.

Slides:



Advertisements
Similar presentations
Bruce Beckles University of Cambridge Computing Service
Advertisements

Python Mini-Course University of Oklahoma Department of Psychology Lesson 26 Classes and Objects 6/16/09 Python Mini-Course: Lesson 26 1.
Tail Recursion. Problems with Recursion Recursion is generally favored over iteration in Scheme and many other languages – It’s elegant, minimal, can.
CSE341: Programming Languages Lecture 16 Datatype-Style Programming With Lists or Structs Dan Grossman Winter 2013.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
CS0007: Introduction to Computer Programming Introduction to Classes and Objects.
Rapid GUI Programming with Python and Qt Classes and Modules By Raed S. Rasheed Classes and Modules By Raed S. Rasheed 1.
Useful Patterns & Idioms Trent Nelson
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Classes 2 COMPSCI 105 S Principles of Computer Science.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game.
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris
UML Basics & Access Modifier
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
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.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Introduction to Pyrex September 2002 Brian Quinlan
Introduction to Python III CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Python Functions.
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.
Python Overview  Last week Python 3000 was released  Python 3000 == Python 3.0 == Py3k  Designed to break backwards compatibility with the 2.x.
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.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
Introduction to Python III CIS 391: Artificial Intelligence Fall, 2008.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
CSC 205 Java Programming II Defining & Implementing Classes.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 17.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 16: Introduction to C++
Classes COMPSCI 105 SS 2015 Principles of Computer Science.
Python – May 19 Review –What is the difference between: list, tuple, set, dictionary? –When is it appropriate to use each? Creating our own data types:
Function and Function call Functions name programs Functions can be defined: def myFunction( ): function body (indented) Functions can be called: myFunction(
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Python’s Standard Library Part 2 Francis Ryan. Output formatting, 1 repr module – When using large or deeply nested containers, allows better printing.
Making our own Classes and objects  As in real life, we’re now creating classes of objects.  a class that defines basic characteristics and functions.
Useful Python Techniques: A brief introduction to List Comprehensions, Functional Programming, and Generators October 4, 2011 Joe Cross.
Rapid GUI Programming with Python and Qt Classes and Modules By Raed S. Rasheed Classes and Modules By Raed S. Rasheed 1.
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.
INTRO2CS Tirgul 8 1. What We’ll Be Seeing Today  Introduction to Object-Oriented Programming (OOP).  Using Objects  Special methods 2.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
HTML 5 (Part 1) – Start from SCRATCH. HTML 5 – Start from SCRATCH.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
CMSC201 Computer Science I for Majors Lecture 18 – Classes and Modules (Continued, Part 3) Prof. Katherine Gibson Based on slides from the.
Object Oriented Programming
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Object Oriented Programming in Python: Defining Classes
COMPSCI 107 Computer Science Fundamentals
Lecture 6 D&D Chapter 7 & 8 Intro to Classes and Objects Date.
Creating and Deleting Instances Access to Attributes and Methods
Python Classes By Craig Pennell.
Guide to Programming with Python
Passing Parameters by value
G. Pullaiah College of Engineering and Technology
CSC1018F: Object Orientation, Exceptions and File Handling (Tutorial)
Access control Many languages have a notion of 'private' variables that can't be accessed from outside an object. For example, if we were sending someone.
Singleton Pattern Damian Gordon.
Python classes: new and old
Access Control Damian Gordon.
Lecture 18 Python OOP.
Python classes: new and old
Migrating to Object-Oriented Programs
Object-Oriented Design AND CLASS PROPERTIES
Presentation transcript:

Python classes: new and old

New and classic classes  With Python 2.2, classes and instances come in two flavors: old and new  New classes cleaned up the language by Unifying classes and types Allowing all built-in types to be sub-classed  For compatibility, default 2.x class is old style; Python 3 only has new classes  New classes support interesting features  New classes subclass object

New class student class Student(object): “““A new class representing a student””” def __init__(self,n,a): self.full_name = n self.age = a def get_age(self): return self.age

Class property  One neat feature in new classes is the property function property  It’s a better way to manage private attributes, and getter and setter methods  While still keeping access simple  We’ll also see decorators, an interesting featuredecorators

Boxes, little boxes class Box(object): def __repr__(self): return ” " % (self.length, self.width, self.area) class Box1(Box): """A rectangle""" def __init__(self, l=1, w=1): self.length = l self.width = w self.area = l * w

Boxes, little boxes  Ok, but not perfect >>> from box import * >>> b1 = Box1(2, 3) >>> b1 A box with length:2, width:3, area:6 >>> b1.area = 9 >>> b1

Boxes, little boxes  Let’s use a getter method for area class Box2(Box): """A rectangle with area getter""" def __init__(self, l=1, w=1): self.length = l self.width = w def get_area(self): return self.length * self.width def set_area(self, val=1): print "Warning: area is read only!"

Boxes, little boxes  Not without problems, though… >>> from box import * >>> b2 = Box2(2, 3) >>> b2 Traceback (most recent call last): File " ", line 1, in File "box.py", line 5, in __repr__ return " " % (self.length, self.width, self.area) AttributeError: 'Box2' object has no attribute 'area’

Boxes, little boxes  There are two problems that the getter/setter idiom creates  It results in different access patterns for different attributes   If we start with plain attributes and later decide to use getter and setters, we may have a lot of code to change 

Boxes, little boxes  Python solution: property()property() class Box3(Box): """A rectangle with area property""" def __init__(self,l=1,w=1): self.length = l self.width = w def get_area(self): return self.length * self.width def set_area(self, val=1): print "Warning: area is read only!" area = property(get_area, set_area)

Boxes, little boxes  The property() function takes optional args for an attribute’s getter, setter, deleter and doc string property([fget[, fset[, fdel[, doc]]]])  and returns an object  Not providing a setter results in a read- only attribute

Decorated Boxes  Use Python decoratorsdecorators class Box4(Box): """A rectangle with area property""" def __init__(self,l=1,w=1): self.length = l self.width = def area(self): return self.length * def area(self, val=1): print "Warning: area is read only!”

Python Decorators  Python’s decorator is syntactic def bar (x): pass  Is the equivalent of def bar (x): pass bar = foo(bar)  That is: rebind the name bar to the result of calling foo with the function object bar  foo typically returns a modified version of the function bar

Decorator example: trace def trace(f): def new_f(*args) print 'Entering %s%s' % (f.__name__, args) result = f(*args, **kwargs) print 'Exiting %s%s with %s' % (f.__name__, args, result) return result return def sum(n, m): return n + m >>> sum(10,20) Entering sum(10, 20) Exiting sum(10, 20) with >>> sum(10,20) Entering sum(10, 20) Exiting sum(10, 20) with

Decorator example: def fact(n): return 1 if n<2 else n * fact(n-1) >>> fact(4) Entering fact(4,) Entering fact(3,) Entering fact(2,) Entering fact(1,) Exiting fact(1,) with 1 Exiting fact(2,) with 2 Exiting fact(3,) with 6 Exiting fact(4,) with 24 24

Decorated Boxes class Box5(Box): def __init__(self,l=1,w=1): self.length = l self.width = w self._color = def area(self): return self.length * def area(self, val=1): self.length = self.width = def color(self): return def color(self, val): self._color = def color(self): del self._color