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

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

F21SC Industrial Programming: Python: Advanced Language Features

Beyond Blocks: Python Session #1

INTERPRETERS 8. 1 Calculator COMPUTER SCIENCE 61A. November 3, 2016

F21SC Industrial Programming: Python: Classes and Exceptions

F21SC Industrial Programming: Functional Programming in Python

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

Python Tutorial. Day 1

CIS192 Python Programming

C# Fundamentals. Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh

Python memento TI-Smart Grids

Descriptor HowTo Guide Release 3.3.3

C# Data Manipulation

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

Software Development Python (Part B)

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

CSCE 110 Programming I

Motivation. Reflection in C# Case study: Implicit Serialisation. Using implicit serialisation. Hans-Wolfgang Loidl

Object Model Comparisons

C# Data Manipulation

Meta Classes. Chapter 4

Python. Jamie Gabbay (adapted from slides by Hans-Wolfgang Loidl) Semester /16

CS115 - Module 9 - filter, map, and friends

Data Structures (list, dictionary, tuples, sets, strings)

F28HS Hardware-Software Interface: Systems Programming

Introduction to Python programming, II

Downloaded from Chapter 2. Functions

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

F28HS Hardware-Software Interface: Systems Programming

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

RLISTS AND THE ENVIRONMENT MODEL 9

Iterators & Generators

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

Object Oriented Programming in Python 3

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

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

At full speed with Python

PROGRAMMING FUNDAMENTALS

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

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

F21SC Industrial Programming: Python: Python Libraries

python 01 September 16, 2016

Fun with Python Descriptors

Metaprogramming assignment 3

Func%onal Programming in Scheme and Lisp

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

Structure and Interpretation of Computer Programs

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

ENGR 101 Engineering Design Workshop

Programming Languages

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

New York University School of Continuing and Professional Studies Management and Information Technology. Advanced Python. Homework, Session 5

Introduction to: Computers & Programming: Review prior to 1 st Midterm

Func%onal Programming in Scheme and Lisp

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

INTERPRETERS AND TAIL CALLS 9

Python Reference (The Right Way) Documentation

Recurrences and Memoization: The Fibonacci Sequence

6.01: Introduction to EECS 1 Week 2 September 15, 2009

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

INHERITANCE AND INTERFACES 7

CS 234 Python Review Part 2

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

F28HS Hardware-Software Interface: Systems Programming

6. Object-Oriented Programming, II. Programming and Algorithms II Degree in Bioinformatics Fall 2018

Processadors de Llenguatge II. Functional Paradigm. Pratt A.7 Robert Harper s SML tutorial (Sec II)

Getting Started with Python

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

Symbolic Computation and Common Lisp

List Comprehensions. Function Definitions. This is the same as mapping the doubling function on the list [1,2,3], but without an explicit

Python Basics. Nakul Gopalan With help from Cam Allen-Lloyd

CNRS ANF PYTHON Objects everywhere

Introduction to Python Programming

Modules and scoping rules

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

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

Python as a First Programming Language Justin Stevens Giselle Serate Davidson Academy of Nevada. March 6th, 2016

Lecture #5: Higher-Order Functions. A Simple Recursion. Avoiding Recalculation. Redundant Calculation. Tail Recursion and Repetition

Module 10: Imperative Programming, Modularization, and The Future

Programming with Python

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

Week 2. Classes and Objects

Alastair Burt Andreas Eisele Christian Federmann Torsten Marek Ulrich Schäfer. October 6th, Universität des Saarlandes. Introduction to Python

Semantics via Syntax. f (4) = if define f (x) =2 x + 55.

CS1 Lecture 3 Jan. 18, 2019

Algorithms and Programming I. Lecture#12 Spring 2015

Structure and Interpretation of Computer Programs

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

Table of Contents. Preface... xxi

Programming I. Course 9 Introduction to programming

Where we are Distributed and Parallel Technology. Union Types. A Tree Structure. t tag node. C Revision (Part II)

self demonstrate two objects and self keyword in each case (inefficient_dict.py)

And Parallelism. Parallelism in Prolog. OR Parallelism

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

CS1 Lecture 3 Jan. 22, 2018

CIS192 Python Programming

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Transcription:

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 software has been used in producing these slides Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 1 / 21 Overloading Operators such as +, <= and functions such as abs, str and repr can be defined for your own types and classes. # constructor def init (self, coord): self.coord = coord # turns the object into string def str (self): return str(self.coord) v1 = Vector([1,2,3]) # performs conversion to string as above print (v1) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 2 / 21 Overloading Overloading arithmetic operations # constructor def init (self, coord): self.coord = coord # turns the object into string: use <> as brackets, and ; as separator def str (self): s = "<" if len(self.coord)==0: return s+">" else: s = s+str(self.coord[0]) for x in self.coord[1:]: s = s+";"+str(x); return s+">" v1 = Vector([1,2,3]); print (v1) import math # sqrt import operator # operators as functions... def abs (self): Vector length (Euclidean norm). return math.sqrt(sum(x*x for x in self.coord)) def add (self, other): Vector addition. return map(operator.add, self.coord, other.coord) print(abs(v1)) print(v1 + v1) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 3 / 21 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 4 / 21

Overloading of non-symmetric operations Overloading of indexing Scalar multiplication for vectors can be written either v1 * 5 or 5 * v1.... def mul (self, scalar): Multiplication with a scalar from the right. return map(lambda x: x*scalar, self.coord) def rmul (self, scalar): Multiplication with a scalar from the left. return map(lambda x: scalar*x, self.coord) v1 * 5 calls v1. mul(5). 5 * v1 calls v1. rmul(5). Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 5 / 21 Indexing and segment-notation can be overloaded as well: def getitem (self, index): Return the coordinate with number index. return self.coord[index] def getslice (self, left, right): Return a subvector. return Vector(self.coord[left:right]) print v1[2] print v1[0:2] Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 6 / 21 Exercise (optional) Define a class Matrix and overload the operations + und * to perform addition and multiplication on matrices. Define further operations on matrices, such as m.transpose(), str(m), repr(m). Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 7 / 21 Types type(v) yields the type of v. Type-membership can be tested like this isinstance(val,typ). E.g. >>> isinstance(5, float) False >>> isinstance(5., float) This check observes type-membership in the parent class. E.g. >>> isinstance(nameerror(), Exception) issubclass checks the class-hierarchy. >>> issubclass(nameerror, Exception) >>> issubclass(int, object) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 8 / 21

Manual Class Generation type(name,superclasses,attributes) creates a class object with name name, parent classes superclasses, and attributes attributes. C = type( C,(),{}) corresponds to class C: pass. Methods can be passed as attributes: def f (self, coord): self.coord = coord Vec = type( Vec, (object,), { init : f}) Manual class generation is useful for meta-programming, i.e. programs that generate other programs. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 9 / 21 Properties Properties are attributes for which read, write and delete operations are defined. Construction: property(fget=none, fset=none, fdel=none, doc=none) class Rectangle(object): def init (self, width, height): self.width = width self.height = height # this generates a read only property area = property( lambda self: self.width * self.height, doc="rectangle area (read only).") # anonymous fun print("area of a 5x2 rectange: ", Rectangle(5,2).area) Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 10 / 21 Controlling Attribute Access Static Methods Access to an attribute can be completely re-defined. This can be achieved as follows: getattribute (self, attr) setattr (self, attr, value) delattr (self, attr) : Lists without append class listnoappend(list): def getattribute (self, name): if name == append : raise AttributeError return list. getattribute (self, name) A class can define methods, that don t use the current instance (self). Class methods can access class attributes, as usual. Static methods can t do that!. class Static: # static method def bla(): print ("Hello, world!") hello = staticmethod( bla) The static method hello can be called like this: Static.hello() Static().hello() Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 11 / 21 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 12 / 21

Class/Instance Methods A class or instance method takes as first argument a reference to an instance of this class. class Static: val = 5 # class method def sqr(c): return c.val * c.val sqr = classmethod(sqr) Static.sqr() Static().sqr() It is common practice to overwrite the original definition of the method, in this case sqr. Question: What happens if we omit the line with classmethod above? Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 13 / 21 Function Decoration The pattern def f(args):... f = modifier(f) has the following special syntax: @modifier def f(args):... We can rewrite the previous example to: class Static: val = 5 # class method @classmethod def sqr(c): return c.val * c.val More examples of using modifiers: Memoisation, Type-checking. Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 14 / 21 To visualise the function calls, we define a decorator for tracing: We want a version of Fibonacci (below), that remembers previous results ( memoisation ). def fib(n): """Compute Fibonacci number of @n@.""" if n==0 or n==1: return 1 else: return fib(n-1)+fib(n-2) NB: This version performs an exponential number of function calls! def trace(f): """Perform tracing on function @func@.""" def trace_func(n): print("++ computing", f. name," with ", str(n)) return f(n) return trace_func and we attach this decorator to our fib function: @trace def fib(n):... Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 15 / 21 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 16 / 21

Here is the implementation of the decorator: Now, we implement memoisation as a decorator. Idea: Whenever we call fib, we remember input and output. Before calling a fib, we check whether we already have an output. We use a dictionary memo_dict, to store these values. This way, we never compute a Fibonacci value twice, and runtime becomes linear, rather than exponential! def memoise(f): """Perform memoisation on function @func@.""" def memo_func(n, memo_dict=dict()): if n in memo_dict.keys(): return memo_dict[n] else: print("++ computing", f. name," with ", str(n)) x = f(n) memo_dict[n] = x print(".. keys in memo_dict: ", str(memo_dict.keys()) return x return memo_func Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 17 / 21 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 18 / 21 Interpretation We attach this decorator to the fib function like this: @memoise def fib(n):... Nothing else in the code changes! See online sample memofib.py Strings can be evaluated using the function eval, which evaluates string arguments as Python expressions. >>> x = 5 >>> eval ("x") 5 >>> f = lambda x: eval("x * x") >>> f(4) 16 The command exec executes its string argument: >>> exec("print(x+1)") 5 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 19 / 21 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 20 / 21

Compilation This performs compilation of strings to byte-code: >>> c = compile("map(lambda x:x*2,range(10))", # code pseudo-file.py, # filename for error msg eval ) # or exec (module) or single (stm) >>> eval(c) <map object at 0x7f2e990e3d30> >>> for i in eval(c): print(i) 0... Beware of indentation in the string that you are composing! >>> c2 = compile(... def bla(x):... print x*x... return x... bla(5)..., pseudo, exec ) >>> exec c2 25 Hans-Wolfgang Loidl (Heriot-Watt Univ) Python 2016/17 21 / 21