Fun with Python Descriptors

Size: px
Start display at page:

Download "Fun with Python Descriptors"

Transcription

1 Fun with Python Descriptors Author: Jeff Rush Date: include directive disabled... include:: <s5defs.txt> Overview What are descriptors? Implementation: attribute watcher Implementation: property() builtin Implementation: methods over functions Implementation: StaticMethod builtin Implementation: ClassMethod builtin Lazy Properties Cached Properties What is a Descriptor? only for new-style objects an object that implements magic methods get set delete these methods override normal attribute lookup Why do Descriptors Exist? to simplify the underlying C code make it easier to override attribute lookup Example Uses of Descriptors properties methods static methods class methods super() 1

2 The Descriptor Protocol name # attribute s name doc # attribute s docstring [descriptor]. get (self, obj, type=none) -> value [descriptor]. set (self, obj, value) -> None [descriptor]. delete (self, obj) -> None If both get and set are defined then it is a data descriptor (like simple attributes) If just get are defined then it is a non-data-descriptor (like methods) Attribute Lookup Precedence Rules Important: 1. data descriptors 2. instance variables via dict 3. non-data descriptors 4. getattr method But What About The Old Way? getattr (name) -> value still there in new-style classes getattribute (name) -> value added for new-style classes getattribute is always called; getattr is only called if the name is not found in the instance dictionary. Making a Read-Only Data Descriptor define both get and set have set raise an AttributeError Attribute Lookup Machinery differs between classes, instances and super() search the instance dict then the class s dict then each base class dict excludes metaclasses overriding getattribute breaks descriptors 2

3 Descriptor Machinery for Classes Implemented in type. Example: A.x getattribute descriptor = A. class.x descriptor. get (instance=none, instance_type=self) def getattribute (self, key): v = object. getattribute (self, key) if hasattr(v, get ): return v. get (None, self) return v Descriptor Machinery for Instances Implemented in object. Example: a.x getattribute descriptor = a. class.x descriptor. get (instance=a, instance_type=type(a)) Descriptor Machinery for super() Implemented in super(). getattribute Example: super(a, obj).m() # searches obj. class. mro for (B, A) descriptor = A.m descriptor. get (instance=obj, instance_type=a) Example 1 - Logging Certain Attribute Fetches class RevealAccess(object): def init (self, initvalue=none, name= var ): self.value = initvalue self.name = name def get (self, instance, instance_type): print "Fetching:", self.name return self.value def set (self, instance, value): print "Setting:", self.name self.value = value class TargetClass(object): x = RevealAccess(10, var x ) 3

4 Use of Descriptors in property() builtin class MyClass(object): def x(self): def get(self): return self. x def set(self, value): self. x = value def del(self): del self. x x = property(x.get, x.set, x.del, " x property") Example 2 - Implementation of property class Property(object): def init (self, fget=none, fset=none, fdel=none, doc=none): self.fget = fget self.fset = fset self.fdel = fdel self. doc = doc if instance is None: return self if self.fget is None: raise AttributeError, "unreadable attribute" return self.fget(instance) (continued) Example 2 - cont d def set (self, instance, value): if self.fset is None: raise AttributeError, "can t set attribute" self.fset(instance, value) def delete (self, instance): if self.fdel is None: raise AttributeError, "can t delete attribute" self.fdel(instance) Example 3 - Implementation of Python Methods Python is built upon a function-based environment. features by binding functions into methods. Class dict store methods as functions. class FunctionDesc(object): return types.methodtype(self, instance, instance_type) Non-data descriptors add the object-oriented 4

5 class D(object): def f(self, x): # implicit f = FunctionDesc(codeblock) return x d = D() # D. dict [ f ] <function f> # D.f (unbound method) type(d). dict [ f ]. get (None, self) # d.f (bound method) type(d). dict [ f ]. get (d, type(d)) Example 4 - Implementation of StaticMethod builtin Lack any reference to the class or instance. class StaticMethod(object): def init (self, f): self.f = f return self.f Example 4 - Implementation of ClassMethod builtin Lack any reference to the instance but has one to the class. Useful for alternate class constructors, such as Dict.fromkeys(). class ClassMethod(object): def init (self, f): self.f = f if instance_type is None: instance_type = type(instance) def newfunc(*args): return self.f(instance_type, *args) return newfunc Lazy Properties (No Automatic Updates) from blah import LazyProperty class Point(object): def init (self, x, y): self.x, self.y = x, y def radius(self): 5

6 return sqrt(self.x**2 + self.y**2) radius = LazyProperty(radius) point = Point(1.0, 2.0) print point.radius # computes value and stuffs into dict print point.radius # reuses value already in dict del point.radius print point.radius # computes value and stuffs into dict Lazy Properties Calls with Decorators from blah import LazyProperty class Point: def init (self, x, y): self.x, self.y = x, # <---- def radius(self): return sqrt(self.x**2 + self.y**2) Implementation of Lazy Properties class Lazy(object): def init (self, func, name=none): if name is None: name = func. name self.data = (func, name) def get (self, instance, instance_type): if instance is None: return self func, name = self.data value = func(instance) instance. dict [name] = value return value Cached Properties (with Automatic Updates) from blah import CachedProperty class Point(object): def init (self, x, y): self.x, self.y = x, y x, y ) def radius(self): return math.sqrt(self.x**2 + self.y**2) radius = CachedProperty(radius, x, y ) # <---- 6

7 Implementation of Cached Properties ncaches = 1 class CachedProperty(object): def init (self, func, *names): global ncaches ncaches += 1 self.data = (func, names, "_v_cached_property_key_%s" % ncaches, "_v_cached_property_value_%s" % ncaches) def get (self, instance, instance_type): if instance is None: return self func, names, key_name, value_name = self.data key = names and [getattr(instance, name) for name in names] value = getattr(instance, value_name, self) if value is not self: # We have a cached value if key == getattr(instance, key_name, self): return value # Cache is still good! # We need to compute and cache the value value = func(instance) setattr(instance, key_name, key) setattr(instance, value_name, value) return value Questions? PEP 252: Making Types Look More Like Classes PEP 253: Subtyping Built-in Types DFW Pythoneers - November 25,

Descriptor HowTo Guide Release 3.3.3

Descriptor HowTo Guide Release 3.3.3 Descriptor HowTo Guide Release 3.3.3 Guido van Rossum Fred L. Drake, Jr., editor November 17, 2013 Python Software Foundation Email: docs@python.org Contents 1 Abstract ii 2 Definition and Introduction

More information

Discovering Descriptors

Discovering Descriptors Discovering Descriptors Mariano Anaya EuroPython - July 2017 rmariano rmarianoa def Learning about descriptors not only provides access to a larger toolset, it creates a deeper understanding of how Python

More information

Object-oriented programming in Python (2)

Object-oriented programming in Python (2) Programming Languages Week 9 Object-oriented programming in Python (2) College of Information Science and Engineering Ritsumeikan University plan last week: dictionaries vs. objects classes, instances,

More information

Sage Reference Manual: Python technicalities

Sage Reference Manual: Python technicalities Sage Reference Manual: Python technicalities Release 8.1 The Sage Development Team Dec 09, 2017 CONTENTS 1 Various functions to debug Python internals 3 2 Variants of getattr() 5 3 Metaclasses for Cython

More information

Python OOP. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 19, 2010

Python OOP. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 19, 2010 Python OOP Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 19, 2010 Stéphane Vialette (LIGM, Université Paris-Est Marne-la-Vallée) Python OOP October 19, 2010 1 / 59 Outline 1 Introduction

More information

Objects and classes in Python Documentation

Objects and classes in Python Documentation Objects and classes in Python Documentation Release 0.1 Jonathan Fine Sep 27, 2017 Contents 1 Decorators 2 1.1 The decorator syntax......................................... 2 1.2 Bound methods............................................

More information

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19 1 Decorators 2 Descriptors 3 Static Variables 4 Anonymous Classes Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, 2009 1 / 19 Decorator Pattern In object-oriented programming, the

More information

traity Documentation Release Sean Ross-Ross

traity Documentation Release Sean Ross-Ross traity Documentation Release 0.0.1 Sean Ross-Ross August 16, 2016 Contents 1 Traity s API 3 1.1 Events.................................................. 3 1.2 Static Properties.............................................

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object-Oriented Programming Robert Rand University of Pennsylvania February 10, 2016 Robert Rand (University of Pennsylvania) CIS 192 February 10, 2016 1 / 25 Outline 1 Object

More information

What's New in Python 2.2

What's New in Python 2.2 What's New in Python 2.2 LinuxWorld - New York City - January 2002 Guido van Rossum Director of PythonLabs at Zope Corporation guido@python.org guido@zope.com Overview Appetizers Nested Scopes Int/Long

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Introduction Robert Rand University of Pennsylvania September 16, 2015 Robert Rand (University of Pennsylvania) CIS 192 September 16, 2015 1 / 21 Outline 1 Object Orientation

More information

Design and implementation of a RPC library in python

Design and implementation of a RPC library in python 2014-07-18 2014-07-18 1 / 32 2014-07-18 2 / 32 Remote procedure call RPC s with methods s Request from a client to a service Reply from a service to a client 2014-07-18 3 / 32 Remote procedure call RPC

More information

Positional, keyword and default arguments

Positional, keyword and default arguments O More on Python n O Functions n Positional, keyword and default arguments in repl: >>> def func(fst, snd, default="best!"):... print(fst, snd, default)... >>> func(snd='is', fst='python') ('Python', 'is',

More information

Friday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014

Friday, 11 April 14. Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014 Advanced methods for creating decorators Graham Dumpleton PyCon US - April 2014 Intermission Rant about the history of this talk and why this topic matters. Python decorator syntax @function_wrapper def

More information

CNRS ANF PYTHON Objects everywhere

CNRS ANF PYTHON Objects everywhere CNRS ANF PYTHON Objects everywhere Marc Poinot Numerical Simulation Dept. Outline Python Object oriented features Basic OO concepts syntax More on Python classes multiple inheritance reuse introspection

More information

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

COMP519 Web Programming Lecture 21: Python (Part 5) Handouts COMP519 Web Programming Lecture 21: Python (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Functions

More information

Slightly Advanced Python:

Slightly Advanced Python: Slightly Advanced Python: some well-documented internals http://www.aleax.it/ut_pyadv.pdf 2008 Google -- aleax@google.com Audience level for this talk Shu ("Retain") Ha ("Detach") Ri ("Transcend") 2 This

More information

CSC326 Meta Programming i. CSC326 Meta Programming

CSC326 Meta Programming i. CSC326 Meta Programming i CSC326 Meta Programming ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 Class Factory 1 3 Meta Class 1 4 Decorator 2 5 Misuse of Decorators 3 6 Using Decorators

More information

Python Decorators. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 28, 2010

Python Decorators. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 28, 2010 Python Decorators Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 28, 2010 Stéphane Vialette (LIGM, Université Paris-Est Marne-la-Vallée) Python Decorators October 28, 2010 1 / 37

More information

Python for Finance. Advanced Features. Andras Niedermayer

Python for Finance. Advanced Features. Andras Niedermayer Python for Finance Advanced Features Andras Niedermayer Objects of Interest object oriented programming (Wikipedia) Definition (Object-oriented Programming) Object-oriented programming (OOP) is a programming

More information

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2 61A Extra Lecture 6 Announcements Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2 Homework 3 is to complete an extension to Project 4 Due at the same time as Project

More information

Advanced Python Subjects. By Imri Goldberg plnnr.com

Advanced Python Subjects. By Imri Goldberg   plnnr.com Advanced Python Subjects By Imri Goldberg www.algorithm.co.il plnnr.com Introduction Many people I know come to Python from C/C++. Including me! They bring with them many unpythonic idioms: inheritance

More information

DSC 201: Data Analysis & Visualization

DSC 201: Data Analysis & Visualization DSC 201: Data Analysis & Visualization Classes Dr. David Koop Tuple, List, Dictionary, or Set? [1,2,"abc"] 2 Tuple, List, Dictionary, or Set? {"a", 1, 2} 3 Tuple, List, Dictionary, or Set? {} 4 Tuple,

More information

Software Development Python (Part B)

Software Development Python (Part B) Software Development Python (Part B) Davide Balzarotti Eurecom 1 List Comprehension It is a short way to construct a list based on the content of other existing lists Efficient Elegant Concise List comprehensions

More information

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

More information

Overloading. F21SC Industrial Programming: Python: Advanced Language Features. Overloading. Overloading arithmetic operations

Overloading. F21SC Industrial Programming: Python: Advanced Language Features. Overloading. Overloading arithmetic operations F21SC Industrial Programming: Python: Advanced Language Features Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2016/17 0 No proprietary

More information

Review 2. Classes and Subclasses

Review 2. Classes and Subclasses Review 2 Classes and Subclasses Class Definition class (): """Class specification""" class variables (format: Class.variable) initializer ( init ) special method definitions

More information

LECTURE 6. Advanced Functions and OOP

LECTURE 6. Advanced Functions and OOP LECTURE 6 Advanced Functions and OOP FUNCTIONS Before we start, let s talk about how name resolution is done in Python: When a function executes, a new namespace is created (locals). New namespaces can

More information

Lessons on Python Classes and Objects

Lessons on Python Classes and Objects Lessons on Python Classes and Objects Walter Didimo [ 120 minutes ] Outline We will introduce basic concepts about classes and objects in Python a comprehensive lesson on this topic would require much

More information

Harness the power of Python magic methods and lazy objects.

Harness the power of Python magic methods and lazy objects. Harness the power of Python magic methods and lazy objects. By Sep Dehpour Aug 2016 zepworks.com sep at zepworks.com https://github.com/seperman/redisworks Lazy Loading Defer initialization of an object

More information

Introduction to Python programming, II

Introduction to Python programming, II Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class

More information

It's not magic: Descriptors exposed. (the descriptors, not us, don't scare) Facundo Joaquín

It's not magic: Descriptors exposed. (the descriptors, not us, don't scare) Facundo Joaquín It's not magic: Descriptors exposed (the descriptors, not us, don't scare) Joaquín Sorianello @_joac Facundo Batista @facundobatista Let's play Meta-play class Strength: class Character: def break_wall(self,

More information

Exceptions. raise type(message) raise Exception(message)

Exceptions. raise type(message) raise Exception(message) Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/.0

More information

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes chapter 11 Code Listing 11.1 First Class Introduction to Classes What is a class? If you have done anything in computer science before, you likely will have heard the term object oriented programming (OOP)

More information

Object Model. Object Oriented Programming Spring 2015

Object Model. Object Oriented Programming Spring 2015 Object Model Object Oriented Programming 236703 Spring 2015 Class Representation In Memory A class is an abstract entity, so why should it be represented in the runtime environment? Answer #1: Dynamic

More information

Week 2. Classes and Objects

Week 2. Classes and Objects Week 2 Classes and Objects Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0

More information

WHY YOU DON'T NEED DESIGN PATTERNS IN PYTHON? EuroPython 2017

WHY YOU DON'T NEED DESIGN PATTERNS IN PYTHON? EuroPython 2017 WHY YOU DON'T NEED DESIGN PATTERNS IN PYTHON? EuroPython 2017 EVERYTHING STARTS WITH A STORY... Zen of Python! STORY OF A PYTHON DEVELOPER TDD FOR THE WIN!!! Readability first! Thousands+ lines of code

More information

LECTURE 6. Advanced Functions and OOP

LECTURE 6. Advanced Functions and OOP LECTURE 6 Advanced Functions and OOP FUNCTIONS Before we start, let s talk about how name resolution is done in Python: When a function executes, a new namespace is created (locals). New namespaces can

More information

Overloading. F21SC Industrial Programming: Python: Advanced Language Features. Overloading. Overloading arithmetic operations

Overloading. F21SC Industrial Programming: Python: Advanced Language Features. Overloading. Overloading arithmetic operations F21SC Industrial Programming: Python: Advanced Language Features Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2015/16 0 No proprietary

More information

Dangerously Advanced Python

Dangerously Advanced Python Dangerously Advanced Python Mike Verdone for Protospace, Calgary May 2009 http://mike.verdone.ca/ Introspection and Metaprogramming Introspection: Programs that can interrogate their own data structures

More information

61A Lecture 16. Wednesday, October 5

61A Lecture 16. Wednesday, October 5 61A Lecture 16 Wednesday, October 5 Policy Changes Based on the Survey Homework can now be completed in pairs, if you wish. Every individual should still submit his/her own homework Please write your partner's

More information

Context-Oriented Programming with Python

Context-Oriented Programming with Python Context-Oriented Programming with Python Martin v. Löwis Hasso-Plattner-Institut an der Universität Potsdam Agenda Meta-Programming Example: HTTP User-Agent COP Syntax Implicit Layer Activation Django

More information

Meta Classes. Chapter 4

Meta Classes. Chapter 4 Chapter 4 Meta Classes Python classes are also objects, with the particularity that these can create other objects (their instances). Since classes are objects, we can assign them to variables, copy them,

More information

CS 11 python track: lecture 4

CS 11 python track: lecture 4 CS 11 python track: lecture 4 Today: More odds and ends assertions "print >>" syntax more on argument lists functional programming tools list comprehensions More on exception handling More on object-oriented

More information

Object-Oriented Python

Object-Oriented Python Object-Oriented Python Everything is an object. Every object has a value. a type. an identity. a namespace. CS105 Python def initstudent(student, eid): global A class is like a namespace. CS105 Python

More information

Computational Mathematics with Python

Computational Mathematics with Python Numerical Analysis, Lund University, 2015 1 Computational Mathematics with Python Unit 7: Object oriented programming with classes Numerical Analysis, Lund University Lecturer: Claus Führer 2015 Classes

More information

python-aspectlib Release 0.5.0

python-aspectlib Release 0.5.0 python-aspectlib 0.5.0 Release 0.5.0 March 17, 2014 Contents i ii aspectlib is an aspect-oriented programming, monkey-patch and decorators library. It is useful when changing behavior in existing code

More information

Advanced Python. generators, decorators, context managers. Zbigniew Jędrzejewski-Szmek. George Mason University

Advanced Python. generators, decorators, context managers. Zbigniew Jędrzejewski-Szmek. George Mason University Advanced Python generators, decorators, context managers Zbigniew Jędrzejewski-Szmek George Mason University Python Summer School, Zürich, September 05, 2013 Version Zürich-98-ge13be00 This work is licensed

More information

F21SC Industrial Programming: Python: Advanced Language Features

F21SC Industrial Programming: Python: Advanced Language Features F21SC Industrial Programming: Python: Advanced Language Features Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2017/18 0 No proprietary

More information

Refreshing last time

Refreshing last time Refreshing last time The Big Idea A hash table is an array of buckets To store something in table: Hash key, then put value in bucket To look up Hash key, go to bucket and find value Empty An empty hash

More information

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012 CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012 COMPUTER SCIENCE IN THE NEWS http://www.iospress.nl/ios_news/music to my eyes device converting

More information

Object Model Comparisons

Object Model Comparisons Object Model Comparisons 1 Languages are designed, just like programs Someone decides what the language is for Someone decides what features it's going to have Can't really understand a language until

More information

The Pyth Language. Administrivia

The Pyth Language. Administrivia Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.

More information

Introduction to Python programming, II

Introduction to Python programming, II GC3: Grid Computing Competence Center Introduction to Python programming, II (with a hint of MapReduce) Riccardo Murri Grid Computing Competence Center, University of Zurich Oct. 10, 2012 Today s class

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

CS 11 python track: lecture 2

CS 11 python track: lecture 2 CS 11 python track: lecture 2 Today: Odds and ends Introduction to object-oriented programming Exception handling Odds and ends List slice notation Multiline strings Docstrings List slices (1) a = [1,

More information

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010 The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 11 Introduction to Classes class Student(object): """Simple Student class.""" def init (self,first='', last='', id=0): # init

More information

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers Lecture 27 Lecture 27: Regular Expressions and Python Identifiers Python Syntax Python syntax makes very few restrictions on the ways that we can name our variables, functions, and classes. Variables names

More information

Using Python for a Large Software Project. Andrew Rowley and Alan Stokes SpiNNaker Team, APT, University of Manchester

Using Python for a Large Software Project. Andrew Rowley and Alan Stokes SpiNNaker Team, APT, University of Manchester Using Python for a Large Software Project Andrew Rowley and Alan Stokes SpiNNaker Team, APT, University of Manchester The SpiNNaker Project The SpiNNaker Project The SpiNNaker Project - Software Python

More information

python-aspectlib Release 0.4.1

python-aspectlib Release 0.4.1 python-aspectlib 0.4.1 Release 0.4.1 May 03, 2014 Contents i ii aspectlib is an aspect-oriented programming, monkey-patch and decorators library. It is useful when changing behavior in existing code is

More information

CS558 Programming Languages Winter 2013 Lecture 8

CS558 Programming Languages Winter 2013 Lecture 8 OBJECT-ORIENTED PROGRAMMING CS558 Programming Languages Winter 2013 Lecture 8 Object-oriented programs are structured in terms of objects: collections of variables ( fields ) and functions ( methods ).

More information

Lecture #15: OOP. A means of defining and using operations specific to these objects.

Lecture #15: OOP. A means of defining and using operations specific to these objects. Lecture #15: OOP Just as def defines functions and allows us to extend Python with new operations, class defines types and allows us to extend Python with new kinds of data. What do we want out of a class?

More information

Python Metaclasses: Who? Why? When?

Python Metaclasses: Who? Why? When? Python Metaclasses: Who? Why? When? [Metaclasses] are deeper magic than 99% of users should ever worry about. If you wonder whether you need them, you don't (the people who actually need them know with

More information

THE AUSTRALIAN NATIONAL UNIVERSITY Final Examination November COMP1730 / COMP6730 Programming for Scientists

THE AUSTRALIAN NATIONAL UNIVERSITY Final Examination November COMP1730 / COMP6730 Programming for Scientists THE AUSTRALIAN NATIONAL UNIVERSITY Final Examination November 2016 COMP1730 / COMP6730 Programming for Scientists Study Period: 15 minutes Time Allowed: 3 hours Permitted Materials: One A4 page (1 sheet)

More information

Slides from INF3331 lectures - Python class programming

Slides from INF3331 lectures - Python class programming Slides from INF3331 lectures- Python class programming p. 1/53 Slides from INF3331 lectures - Python class programming Ola Skavhaug, Joakim Sundnes and Hans Petter Langtangen Dept. of Informatics, Univ.

More information

CS61A Notes Week 13: Interpreters

CS61A Notes Week 13: Interpreters CS61A Notes Week 13: Interpreters Read-Eval Loop Unlike Python, the result of evaluating an expression is not automatically printed. Instead, Logo complains if the value of any top-level expression is

More information

CIS 192: Lecture 9 Working with APIs

CIS 192: Lecture 9 Working with APIs CIS 192: Lecture 9 Working with APIs Lili Dworkin University of Pennsylvania Last Week s Quiz Consider the code l = (i for i in range(10)) What happens if I type l[0]? >>> l = (i for i in range(10)) >>>

More information

Outline. 1 Introduction. 2 Meta-Classes in Python. 3 Meta-Classes vs. Traditional OOP. Meta-Classes. Guy Wiener. Introduction. Meta-Classes in Python

Outline. 1 Introduction. 2 Meta-Classes in Python. 3 Meta-Classes vs. Traditional OOP. Meta-Classes. Guy Wiener. Introduction. Meta-Classes in Python Outline 1 2 3 Outline 1 2 3 What is Meta-Programming? Definition Meta-Program A program that: One of its inputs is a program (possibly itself) Its output is a program Meta-Programs Nowadays Compilers Code

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2005 P. N. Hilfinger Project #2: Static Analyzer for Pyth Due: Wednesday, 6 April

More information

Object-Oriented Jython

Object-Oriented Jython Object-Oriented Jython This chapter is going to cover the basics of object-oriented programming. We ll start with covering the basic reasons why you would want to write object-oriented code in the first

More information

COLUMNS. Thinking about Type Checking

COLUMNS. Thinking about Type Checking DAVID BEAZLEY David Beazley is an open source developer and author of the Python Essential Reference (4th Edition, Addison-Wesley, 2009). He is also known as the creator of Swig (http://www.swig.org) and

More information

CSC148-Section:L0301

CSC148-Section:L0301 CSC148-Section:L0301 Week#1-Wednesday Instructed by AbdulAziz Al-Helali a.alhelali@mail.utoronto.ca Office hours: Wednesday 11-1, BA2230. Slides adapted from Professor Danny Heap and Jacqueline Smith slides

More information

Programming Languages

Programming Languages CSE 130 : Spring 2011 Programming Languages Lecture 13: What s in a Name? Ranjit Jhala UC San Diego Next: What s in a name? More precisely: How should programmer think of data What does a variable x really

More information

Objects and Classes APRIL 23 RD 2012

Objects and Classes APRIL 23 RD 2012 Objects and Classes APRIL 23 RD 2012 Object-Oriented Programming: Example Suppose your program needs to maintain millions of polygons. This is something that graphics programs might have to do because

More information

Classes and Objects. Inheritance

Classes and Objects. Inheritance Copyright Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See http://software-carpentry.org/license.html for more information. Interpolating time series signals

More information

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

More information

Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name?

Next: What s in a name? Programming Languages. Data model in functional PL. What s in a name? CSE 130 : Fall Lecture 13: What s in a Name? Next: What s in a name? CSE 13 : Fall 211 Programming Languages Lecture 13: What s in a Name? More precisely: How should programmer think of data What does a variable x really mean? Ranjit Jhala UC San

More information

PYTHON. Cheat Sheet.

PYTHON. Cheat Sheet. PYTHON Cheat Sheet @moshhamedani Primitive Types Variables a = 1 (integer) b = 1.1 (float) c = 1 + 2j (complex) d = a (string) e = True (boolean) Strings x = Python len(x) x[0] x[-1] x[0:3] Formatted strings

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

Lecture 5. Introduction to Python! Lecture 5

Lecture 5. Introduction to Python! Lecture 5 Lecture 5 Introduction to Python Lecture 5 Summary OOP Concepts Object trees Classes Attributes Methods OOP OOP Inheritance Composition Allows a class to inherit the characteristics and behaviour as another

More information

Object Model. Object Oriented Programming Winter

Object Model. Object Oriented Programming Winter Object Model Object Oriented Programming 236703 Winter 2014-5 Class Representation In Memory A class is an abstract entity, so why should it be represented in the runtime environment? Answer #1: Dynamic

More information

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern CSE 399-004: Python Programming Lecture 12: Decorators April 9, 200 http://www.seas.upenn.edu/~cse39904/ Announcements Projects (code and documentation) are due: April 20, 200 at pm There will be informal

More information

Objects CHAPTER 6. FIGURE 1. Concrete syntax for the P 3 subset of Python. (In addition to that of P 2.)

Objects CHAPTER 6. FIGURE 1. Concrete syntax for the P 3 subset of Python. (In addition to that of P 2.) CHAPTER 6 Objects The main ideas for this chapter are: objects and classes: objects are values that bundle together some data (attributes) and some functions (methods). Classes are values that describe

More information

Python 3 Metaprogramming. Requirements

Python 3 Metaprogramming. Requirements Python 3 Metaprogramming David Beazley @dabeaz http://www.dabeaz.com Presented at PyCon'2013, Santa Clara, CA March 14, 2013 1 Requirements Python 3.3 or more recent Don't even attempt on any earlier version

More information

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 22 CLASS MICHAEL GROSSBERG

CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 22 CLASS MICHAEL GROSSBERG CSC102 INTRO TO PROGRAMMING WITH PYTHON LECTURE 22 CLASS MICHAEL GROSSBERG TYPES INT BOOLEAN FLOAT COMPLEX STRINGS SETS DICTIONARIES LISTS I WANT MY OWN TYPES! CLASSES = DIY TYPES BASIS OF OBJECT ORIENTED

More information

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

More information

Download Python from Any version will do for this class

Download Python from  Any version will do for this class Let s Start Python Let s Start! Download Python from www.python.org Any version will do for this class By and large they are all mutually compatible Recommended version: 2.1.1 or 2.2 Oldest version still

More information

Object Oriented Programming Enthought, Inc. 97

Object Oriented Programming Enthought, Inc. 97 Object Oriented Programming 97 Classes A reusable collection of behavior and data Definition Subclasses Properties 98 Modeling a Power Plant ATTRIBUTES # Data that describes the # modeled "object" name:

More information

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013 , part Deux CSE 231, Rich Enbody Three Groups Users Programmers Class Designers 1 Getters and Setters getters: methods that fetch the value setters: methods set a value 2 GetterSetter Example Why do this?

More information

Data Structures I: Linked Lists

Data Structures I: Linked Lists Lab 4 Data Structures I: Linked Lists Lab Objective: Analyzing and manipulating data are essential skills in scientific computing. Storing, retrieving, and rearranging data take time. As a dataset grows,

More information

Advanced Python. decorators, generators, context managers. Zbigniew Jędrzejewski-Szmek. Institute of Experimental Physics University of Warsaw

Advanced Python. decorators, generators, context managers. Zbigniew Jędrzejewski-Szmek. Institute of Experimental Physics University of Warsaw Advanced Python decorators, generators, context managers Zbigniew Jędrzejewski-Szmek Institute of Experimental Physics University of Warsaw Python Summer School St Andrews, September 11, 2011 Version AP_version_2011

More information

Python Tips and Tricks

Python Tips and Tricks Tips and Tricks Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée November 7, 2012 Stéphane Vialette (LIGM, Université Paris-Est Marne-la-Vallée) Tips and Tricks November 7, 2012 1 / 39 Lists

More information

Week 8 Lecture: Programming

Week 8 Lecture: Programming Week 8 Lecture: Introduction to Object Oriented Programming Introduction to Programming for GIS & Remote Sensing GEO6938 1469 GEO4938 147A Objects: You ve Been Exposed! Modularization, you know about it

More information

Python Programming: Lecture 4 Object Oriented Programming

Python Programming: Lecture 4 Object Oriented Programming Python Programming: Lecture 4 Object Oriented Programming Lili Dworkin University of Pennsylvania October 3, 2014 Good Question from Last Week >>> def foo(a, b, c):... print a, b, c... >>> foo(1, 2, 3)

More information

Sorting HOW TO Release 2.7.6

Sorting HOW TO Release 2.7.6 Sorting HOW TO Release 2.7.6 Guido van Rossum Fred L. Drake, Jr., editor November 10, 2013 Python Software Foundation Email: docs@python.org Contents 1 Sorting Basics i 2 Key Functions ii 3 Operator Module

More information

TAIL RECURSION, SCOPE, AND PROJECT 4 11

TAIL RECURSION, SCOPE, AND PROJECT 4 11 TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration

More information

Lecture 18. Methods and Operations

Lecture 18. Methods and Operations Lecture 18 Methods and Operations Announcements for This Lecture Assignments A4 Due Thursday at midnight Hopefully you are on Task 4 Extra consultants available Will post A5 on Thursday Written assignment

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Python Tips and Tricks

Python Tips and Tricks Tips and Tricks Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée November 14, 2011 Stéphane Vialette (LIGM, Université Paris-Est Marne-la-Vallée) Tips and Tricks November 14, 2011 1 / 36 Lists

More information