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

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

Lecture #14: OOP. Last modified: Mon Feb 27 15:56: CS61A: Lecture #14 1

CSC148 Intro. to Computer Science

Iterators & Generators

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

String Representations

ITP Programming Languages Chapter 2 Building Abstractions with Data 2.5 Object-Oriented Programming 1. Polymorphism repr, str Interface

61A LECTURE 14 MULTIPLE REPRESENTATIONS

61A LECTURE 14 MULTIPLE REPRESENTATIONS. Steven Tang and Eric Tzeng July 17, 2013

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

Harness the power of Python magic methods and lazy objects.

Beyond Blocks: Python Session #1

CS61A Lecture 21. Amir Kamil UC Berkeley March 11, 2013

PIC 16: Iterators and Generators

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Introduction to Python (All the Basic Stuff)

Lecture #12: Mutable Data. map rlist Illustrated (III) map rlist Illustrated. Using Mutability For Construction: map rlist Revisited

Working with classes and objects COSC346

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

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

CIS192 Python Programming

Programming with Python

Lecture #12: Mutable Data. Last modified: Sun Feb 19 17:15: CS61A: Lecture #12 1

Lecture #12: Immutable and Mutable Data. Last modified: Mon Feb 22 16:33: CS61A: Lecture #12 1

Python for C programmers

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

Sequence Types FEB

CIS192 Python Programming

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

Intro. Scheme Basics. scm> 5 5. scm>

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

Objects. say something to express one's disapproval of or disagreement with something.

MEMOIZATION, RECURSIVE DATA, AND SETS

CIS192 Python Programming

Lecture #7: Recursion (and a data structure)

Lecture #21: Search Trees, Sets. Last modified: Tue Mar 18 18:15: CS61A: Lecture #21 1

CS1 Lecture 3 Jan. 22, 2018

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

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

CIS192 Python Programming

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

61A Lecture 16. Wednesday, October 5

COMPSCI 105 S Principles of Computer Science. Classes 3

Jython. secondary. memory

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

Lecture #24: Programming Languages and Programs

STRUCTURE AND INTERPRETATION COMPUTER PROGRAMS >>> COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 23 Py TODAY REVIEW: INTERPRETATION 7/26/2012 READ PRINT

STRUCTURE AND INTERPRETATION COMPUTER PROGRAMS COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 23 Py TODAY 7/26/2012

Structure and Interpretation of Computer Programs

CIS192 Python Programming

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

DATA ABSTRACTION 5. February 21, 2013

Fundamentals of Programming. Week 11 - Lecture 1: OOP Part 2.

SCHEME AND CALCULATOR 5b

Lecture #23: Conversion and Type Inference

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

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

SCHEME INTERPRETER GUIDE 4

Lecture #11: Immutable and Mutable Data. Last modified: Sun Feb 19 17:03: CS61A: Lecture #11 1

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

TUPLES AND RECURSIVE LISTS 5

CS1 Lecture 3 Jan. 18, 2019

python 01 September 16, 2016

CS61A Lecture 23 Py. Jom Magrotker UC Berkeley EECS July 26, 2012

CSI33 Data Structures

CSE 341, Spring 2011, Final Examination 9 June Please do not turn the page until everyone is ready.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Unit Tests. # Store the result of a boolean expression in a variable. >>> result = str(5)=='5'

Lecture 16: Static Semantics Overview 1

Python Tutorial. Day 1

Object Oriented Programming in Python 3

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

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

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Comp Exam 1 Overview.

The Pyth Language. Administrivia

Python for Finance. Advanced Features. Andras Niedermayer

CS 1110: Introduction to Computing Using Python Loop Invariants

Student Number: Comments are not required except where indicated, although they may help us mark your answers.

Introduction to Python! Lecture 2

INHERITANCE AND INTERFACES 7

Algorithms in Systems Engineering ISE 172. Lecture 5. Dr. Ted Ralphs

Python 1: Intro! Max Dougherty Andrew Schmitt

Final Exam Version A

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

INTERPRETERS AND TAIL CALLS 9

Unit E Step-by-Step: Programming with Python

CSE : Python Programming

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators

Intro. Classes & Inheritance

Text Input and Conditionals

Software Development Python (Part B)

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

CS61A Lecture 36. Soumya Basu UC Berkeley April 15, 2013

Advanced Python. Executive Summary, Session 1

Lecture 02 Making Decisions: Conditional Execution

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

Outline. LList: A Linked Implementation of a List ADT Iterators Links vs. Arrays In-class work. 1 Chapter 4: Linked Structures and Iterators

Object Oriented Programming

Transcription:

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

Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of the kth occurrence of x (k>=0), or None if there isn t one.""" for i in range(len(l)): if L[i] == x: if k == 0: return i k -= 1 This same function works on lists, tuples, strings, and (if the keys are consecutive integers) dicts. In fact, it works for any list L for which len and indexing work as they do for lists and tuples. That is, find is generic in the type of L. Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 2

Duck Typing A statically typed language (such as Java) requires that you specify a type for each variable or parameter, one that specifies all the operations you intend to use on that variable or parameter. To create a generic function, therefore, your parameters types must be subtypes of some particular interface. You can do this in Python, too, but it is not a requirement. In fact, our find function will work on any object that has len and getitem, regardless of the object s type. This property is sometimes called duck typing: This parameter must be a duck, and if it walks like a duck and quacks like a duck, we ll say it is a duck. Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 3

Example: The repr Method Whentheinterpreterprintsthevalueofanexpression,itmustfirst convert that value to a (printable) string. To do so, it calls the repr () method of the value, which is supposed to return a string that suggests how you d create the value in Python. >>> "Hello" Hello >>> print(repr("hello")) Hello >>> repr("hello") # What does the interpreter print? (As a convenience, the built-in function repr(x) calls the repr method.) User-defined classes can define their own repr method to control how the interpreter prints them. Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 4

Example: The str Method Whentheprintfunctionprintsavalue,itcallsthe str ()method to find out what string to print. The constructor for the string type, str, does the same thing. Again, you can define your own str on a class to control this behavior. (The default is just to call repr ) >>> class rational:... def init (self, num, den):...... def str (self):... if self.numer() == 0: return "0"... elif self.denom() == 1: return str(self.numer())... else: return "{0}/{1}".format(self.numer(), self.denom())... def repr (self):... return "rational({}, {})".format(self.numer(), self.denom())... >>> print(rational(3,4)) 3/4 >>> rational(3,4) rational(3, 4) >>> print(rational(5, 1)) 5 Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 5

Aside: A Small Technical Issue str, repr, and print all call the methods str and repr, ignoring any instance variables of those names. For example, >>> v = rational(3, 4) >>> v. str = lambda x: "FOO!" >>> str(v) 3/4 >>> c. str () FOO! How could you implement str to do this? Hint: As in the homework, type(x) returns the class of x. Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 6

Other Generic Method Names Just as defining str allows you to specify how your class is printed, Python has many other generic connections to its syntax, which allow programmers great flexibility in expressing things. For example, Method Implements getitem (S, k) S[k] setitem (S, k, v) S[k] = v len (S) len(s) bool (S) bool(s) True or False add (S, x) S + x sub (S, x) S - x mul (S, x) S * x ge (S, x) S >= x... getattr (S, N) S.N Attributes setattr (S, N, v) S.N = v Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 7

Properties I ve said that generally, method calls are the preferred way for clients to access an object (rather than direct access to instance variables.) This practice allows the class implementor to hide details of implementation. Still it s cumbersome to have to say, e.g., apoint.getx() rather than apoint.x, and apoint.setx(v) rather than apoint.x = v. To alleviate this, Python introduced the idea of a property object. When a property object is an attribute of an object, it calls a function when it is fetched from its containing object by dot notation. The property object can also be defined to call a different function on assignment to the attribute. Attributes defined as property objects are called computed or managed attributes. Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 8

Properties (Long Form) class rational: def init (self, num, den): g = gcd(num, den) self._num, self._den = num/g, den/g def _getnumer(self): return self._num def _setnumer(self, val): self._num = val / gcd(val, self._denom) numer = property(_getnumer, _setnumer) # Alternatively, # numer = property(_getnumer).setter(_setnumer) As a result, >>> a = rational(3, 4) >>> a.numer # Calls a._getnumer() 3 >>> a.numer = 5 # Calls a._setnumer(5) Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 9

Properties (Short Form) The built-in property function is also a decorator: class rational:... @property def numer(self): return self._num # Equivalent to # def TMPNAME(self): return self._num # numer = property(tmpname) # where TMPNAME is some identifier not used anywhere else. @numer.setter def numer(self, val): # Equivalent to # def TMPNAME(self, val): self._num = val / gcd(val, self._denom) # numer = numer.setter(tmpname) This is a bit obscure, but the idea is that every property object has a setter method that turns out a new property object that governs both getting and setting of a value. Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 10

Iterators The for statement is actually a generic control construct with the following meaning: for x in C: S tmp_iter = C. iter () try: while True: x = tmp_iter. next () S except StopIteration: pass Types that implement iter are called iterable, and those that implement next are iterators. As usual, the builtin functions iter(x) and next(x) are defined to call x. iter () and x. next (). Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 11

Problem: Reconstruct the range class Want Range(1, 10) to give us something that behaves like a Python range, so that for x in Range(1, 10): print(x) prints 1 9. class Range:??? Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 12