CS61A Lecture 20 Object Oriented Programming: Implementation. Jom Magrotker UC Berkeley EECS July 23, 2012

Similar documents
COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 21 Scheme TODAY REVIEW: DISPATCH DICTIONARIES DISPATCH DICTIONARIES 7/27/2012

61A Lecture 16. Wednesday, October 5

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

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 14 Object Oriented Programming TODAY 7/11/2012 WHERE WE WERE: FUNCTIONAL PROGRAMMING

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

COMPUTER SCIENCE IN THE NEWS (TWO YEARS AGO) CS61A Lecture 16 Mutable Data Structures TODAY REVIEW: OOP CLASS DESIGN 7/24/2012

CS61A Lecture 16 Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 16, 2012

CS61A Lecture 9 Immutable Data Structures. Jom Magrotker UC Berkeley EECS July 2, 2012

& Object-Oriented Programming (POOP) Modified from CS61A Summer 2012 Lecture at UC Berkeley

CS61A Lecture 28 Distributed Computing. Jom Magrotker UC Berkeley EECS August 6, 2012

ENVIRONMENT MODEL: FUNCTIONS, DATA 18

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 24 Infinite Sequences LAZY EVALUATION AGENDA 8/7/2012. Jom Magrotker UC Berkeley EECS July 30, 2012

CS61A Lecture 24 Infinite Sequences. Jom Magrotker UC Berkeley EECS July 30, 2012

TUPLES AND RECURSIVE LISTS 5

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 of Computer Programs

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

Lecture 6. COMP1006/1406 (the OOP course) Summer M. Jason Hinek Carleton University

CSE : Python Programming

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

61A Lecture 3. Friday, September 5

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

OBJECT ORIENTED PROGRAMMING 6

CS61B Lecture #7. Announcements:

CS61A Lecture 27 Logic Programming. Jom Magrotker UC Berkeley EECS August 2, 2012

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

YESTERDAY: DISTRIBUTED COMPUTING

CS61A Lecture 29 Parallel Computing. Jom Magrotker UC Berkeley EECS August 7, 2012

61A LECTURE 1 FUNCTIONS, VALUES. Steven Tang and Eric Tzeng June 24, 2013

61A Lecture 9. Friday, September 20

CS61A Lecture 26 Logic Programming. Jom Magrotker UC Berkeley EECS August 1, 2012

61A Lecture 21. Friday, March 13

SCHEME AND CALCULATOR 5b

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

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

Lecture 19. Operators and Abstraction

Programming for Engineers in Python

Announcements. Last modified: Fri Sep 8 00:59: CS61B: Lecture #7 1

1 State, objects, and abstraction

61A LECTURE 8 SEQUENCES, ITERABLES

61A LECTURE 8 SEQUENCES, ITERABLES. Steven Tang and Eric Tzeng July 8, 2013

OBJECT ORIENTED PROGRAMMING 7

OBJECT ORIENTED PROGRAMMING 6

61A LECTURE 15 MEMOIZATION, RECURSIVE DATA, SETS

OBJECT ORIENTED PROGRAMMING 7

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

PREPARING FOR THE FINAL EXAM

COMPUTER SCIENCE IN THE NEWS. CS61A Lecture 30 MapReduce RECAP: REDUCE TODAY MAP AND REDUCE MAP AND REDUCE: EXAMPLE 8/8/2012

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

6.001 Notes: Section 15.1

CS61A Lecture 30 MapReduce

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Lecture #12: Quick: Exceptions and SQL

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

61A Lecture 7. Monday, September 15

Lecture 18. Classes and Types

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

Lecture 2. Object Orientation

Lecture #21: Search and Sets. Last modified: Wed Mar 9 15:44: CS61A: Lecture #21 1

PREPARING FOR PRELIM 2

CSC 443: Web Programming

Math 152: Applicable Mathematics and Computing

61A Lecture 6. Monday, February 2

Patterns Continued and Concluded. July 26, 2017

MEMOIZATION, RECURSIVE DATA, AND SETS

Structure and Interpretation of Computer Programs Spring 2017 Mock Midterm 1

SCHEME INTERPRETER GUIDE 4

Midterm Review. CS61A Summer Katya Stukalova Jerome Baek

Berkeley Scheme s OOP

Lecture 20. Subclasses & Inheritance

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

61A Lecture 4. Monday, September 9

CS61A Lecture 18. Amir Kamil UC Berkeley March 4, 2013

OBJECT ORIENTED PROGRAMMING 5

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

Where The Objects Roam

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

TAIL RECURSION, SCOPE, AND PROJECT 4 11

Programming Languages and Techniques (CIS120)

CSE 341: Programming Languages. Section AC with Nate Yazdani

Strings in Python 1 Midterm#1 Exam Review CS 8: Introduction to Computer Science Lecture #6

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

Programming Paradigms in Python

PREPARING FOR PRELIM 1

CS1004: Intro to CS in Java, Spring 2005

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

INHERITANCE AND NONLOCAL 6

CS3: Introduction to Symbolic Programming. Lecture 5:

CS3: Introduction to Symbolic Programming. Lecture 11: Tree Recursion, beginning lists, and Midterm 2. Spring 2007 Nate Titterton

6.01: Introduction to EECS I

CS 61A Discussion 8: Scheme. March 23, 2017

Programming Exercise 14: Inheritance and Polymorphism

Tutorials. Tutorial every Friday at 11:30 AM in Toldo 204 * discuss the next lab assignment

Object-Oriented Programming

CS1210 Lecture 28 Mar. 27, 2019

Objects and Classes. Chapter 8

CS 11 python track: lecture 2

Programming Languages and Techniques (CIS120)

Structure and Interpretation of Computer Programs

Transcription:

CS61A Lecture 20 Object Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012

COMPUTER SCIENCE IN THE NEWS http://www.theengineer.co.uk/sectors/electronics/news/researchers create memory with one bit per molecule/1013215.article 2

COMPUTER SCIENCE IN THE NEWS http://news.stanford.edu/news/2012/july/computer model organism 071812.html 3

TODAY Review: Dispatch Functions Dispatch Dictionaries OOP Implementation 4

REVIEW: DISPATCH FUNCTIONS We saw that we do not need data structures to store information: we can use functions to accomplish the storage and retrieval of data. 5

REVIEW: DISPATCH FUNCTIONS def make_pair(first, second): def pair(msg, arg=none): nonlocal first, second if msg == first : return first elif msg == second : return second elif msg == set first : first = arg elif msg == set second : second = arg else: return "Message not understood. return pair 6

REVIEW: DISPATCH FUNCTIONS The inner function pair, returned by every call to make pair, represents the pair object. It receives a message as an argument, and responds by dispatching the appropriate piece of code. The function pair is called the dispatch function; this programming style is called message passing. 7

MESSAGE PASSING Enumerating different messages in a conditional statement is not very convenient. Equality tests can be repetitive. We need to write new code for new messages. Can we use something that will take care of the message lookup and code dispatch for us? 8

DISPATCH DICTIONARIES Idea: We will allow ourselves one kind of data structure. In particular, we will represent an object by a dispatch dictionary, where the messages are the keys. 9

DISPATCH DICTIONARIES def make_pair(first, second): pair_dict = { first : first, second : second } return pair_dict How do we create and use pair objects now? 10

DISPATCH DICTIONARIES >>> def make_pair(first, second):... >>> p = make_pair(1, 2) G make_pair p E1 pair_dict first 1 second 2 params: (first, second) body: pair_dict = {... } first 1 second 2 11

>>> p[ first ] 1 DISPATCH DICTIONARIES G make_pair p E1 pair_dict first 1 second 2 params: (first, second) body: pair_dict = {... } first 1 second 2 12

DISPATCH DICTIONARIES >>> p[ first ] = 3 G make_pair p E1 pair_dict first 1 second 2 params: (first, second) body: pair_dict = {... } first 1 second 2 3 13

ANNOUNCEMENTS: MIDTERM 2 Midterm 2 is on Wednesday, July 25. Where? 2050 VLSB. When? 7PM to 9PM. How much? Material covered until, and including, July 19. Closed book and closed electronic devices. One 8.5 x 11 cheat sheet allowed. Group portion is 15 minutes long. If you have a conflict, please let us know by the end of today, July 23. 14

ANNOUNCEMENTS Homework 10 is due Tuesday, July 24. Project 3 is due Thursday, July 26. Homework 11 is due Friday, July 27. Please ask for help if you need to. There is a lot of work in the weeks ahead, so if you are ever confused, consult (in order of preference) your study group and Piazza, your TAs, and Jom. Don t be clueless! 15

OOP IMPLEMENTATION: PREFACE We have discovered how we can create a pair object using just functions and dictionaries. We will now use many of the same ideas to explore how an object oriented programming system can be constructed from scratch. 16

OOP IMPLEMENTATION: PREFACE Things we will implement: Classes and objects Class variables Instance variables Methods Inheritance 17

OOP IMPLEMENTATION: PREFACE Things we will not implement: Dot notation (We will see similar notation though.) Class methods Multiple inheritance Introspection (What class does this object belong to? What attributes does it have?) 18

OOP IMPLEMENTATION We know that everything in Python is an object. Classes and objects have attributes, which map names to values. These values can either be data or functions. Main idea: We represent classes and objects as dictionaries that map attribute names to values. 19

OOP IMPLEMENTATION We start simple and first implement class variables. For example, we want to mimic class Pokemon: total_pokemon = 0 total_pokemon is a class variable. We access its value using the expression Pokemon.total_pokemon. 20

OOP IMPLEMENTATION: CLASS VARIABLES First solution: def make_class(attributes={}, base_class=none): return attributes def make_pokemon_class(): return make_class({ total_pokemon : 0}) 21

OOP IMPLEMENTATION: CLASS VARIABLES def make_class(attributes={}, base_class=none): return attributes def make_pokemon_class(): return make_class({ total_pokemon : 0 }) >>> Pokemon = make_pokemon_class() >>> Pokemon[ total_pokemon ] 0 22

OOP IMPLEMENTATION: INHERITANCE The current solution works. However, we need to modify it to include support for inheritance. Why? If the current class does not have the class variable, its parent classes might have the variable. We need to specify a way to recursively retrieve values for variables that may be defined in parent classes. 23

OOP IMPLEMENTATION: INHERITANCE Idea: We create two inner functions, one that deals with locating the value for the class variable, and another that deals with setting new values for class attributes. Our class now becomes a dispatch dictionary of at least two keys: get and set. 24

OOP IMPLEMENTATION: INHERITANCE Modified solution: def make_class(attributes={}, base_class=none): def get_value(name): To find the value of a class attribute if name in attributes: check if it is already in the return attributes[name] dictionary of attributes. elif base_class is not None: return base_class[ get ](name) def set_value(name, value): attributes[name] = value Otherwise, if there is a parent class, check if the parent class has the class attribute. cls = { get : get_value, set : set_value} return cls A class is still a dictionary! The two new messages get and set allow us to use the general getter and setter functions. 25

OOP IMPLEMENTATION: INHERITANCE How do we use this new definition of a class? >>> Pokemon = make_pokemon_class() >>> Pokemon[ get ]( total_pokemon ) 0 Find the general getter function in the dispatch dictionary and use it to find the value of a certain class variable. >>> Pokemon[ set ]( total_pokemon, 1) Find the general setter function in the dispatch dictionary and use it to set or update the value of a certain class variable. 26

OOP IMPLEMENTATION: INHERITANCE Pokemon[ get ]( total_pokemon ) is equivalent to Pokemon.total_pokemon Pokemon[ set ]( total_pokemon, 1) is equivalent to Pokemon.total_pokemon = 1 We are passing messages to our classes. 27

OOP IMPLEMENTATION: INHERITANCE The new syntax is (unfortunately) more clunky. However, we can now access class variables from parent classes. >>> Pokemon = make_pokemon_class() >>> def make_water_pokemon_class(): return make_class({}, Pokemon) >>> WaterPokemon = make_water_pokemon_class() >>> WaterPokemon[ get ]( total_pokemon ) 0 28

OOP IMPLEMENTATION: OBJECTS Just as we did with classes, we use dictionaries to represent objects: def make_instance(cls): def get_value(name): if name in attributes: return attributes[name] else: return cls[ get ](name) def set_value(name, value): attributes[name] = value What class is this object an instance of? To find the value of an instance attribute check if it is already in the dictionary of attributes. Otherwise, check if the class has a value for the attribute. Dictionary of instance attributes attributes = {} instance = { get : get_value, set : set_value} return instance An instance is a dictionary! The two messages get and set allow us to use the general getter and setter functions. 29

OOP IMPLEMENTATION: OBJECTS Just as we did with classes, we use dictionaries to represent objects: def make_instance(cls): def get_value(name): if name in attributes: return attributes[name] else: return cls[ get ](name) def set_value(name, value): attributes[name] = value Every instance gets its own dictionary of instance attributes. attributes = {} instance = { get : get_value, set : set_value} return instance 30

OOP IMPLEMENTATION: OBJECTS How do we use this definition of an object? >>> Pokemon = make_pokemon_class() >>> pikachu = make_instance(pokemon) >>> pikachu[ set ]( hp, 300) Find the general setter function in the dispatch dictionary >>> pikachu[ get ]( hp ) 300 Find the general getter function in the dispatch dictionary and use it to set or update the value of a certain instance variable. and use it to find the value of a certain instance variable. 31

BREAK http://thedoghousediaries.com/4432 http://thedoghousediaries.com/4400 32

REVIEW: BOUND METHODS A method is bound to an instance. Use the increase_hp method defined for objects of the Pokemon class with self being the ashs_pikachu object and amount being 150. Pokemon.increase_hp(ashs_pikachu, 150) is equivalent to ashs_pikachu.increase_hp(150) Use the increase_hp method of (or bound to) the ashs_pikachu object with amount being 150. 33

BOUND METHODS ashs_pikachu.increase_hp(150) In the expression above, we do not pass in an object as the first argument, even though the definition of increase_hp seems to need it. The first argument to the method increase_hp is already bound to the object ashs_pikachu. 34

BOUND METHODS We have seen a variant of this idea before, during functional programming: def sum_of_squares(a, b): return a*a + b*b def sum_with_25(b): return sum_of_squares(5, b) 35

OOP IMPLEMENTATION: LOOKING AHEAD We would like to eventually have the following (revised) definition of the Pokemon class: def make_pokemon_class(): def init (self, name, owner, hp):... def increase_hp(self, amount):... 36

OOP IMPLEMENTATION: OBJECTS def make_instance(cls): def get_value(name): if name in attributes: return attributes[name] else: value = cls[ get ](name) return bind_method(value, instance) 37

OOP IMPLEMENTATION: OBJECTS def bind_method(value, instance): if callable(value): else: def method(*args): return value(instance, *args) return method return value If the value provided is callable (for example, a function),... make the new bound method where the first argument is bound to the instance given, and all the other arguments remain the same and return this bound method. If the value provided is not callable, return it as is. 38

OOP IMPLEMENTATION: INSTANTIATION AND INITIALIZATION We have seen how we can implement instance variables, class variables, and methods. We are almost done! In Python s OOP system, the expression Pokemon( Pikachu, Ash, 300) both instantiated a new object and initialized its attributes with appropriate values. The constructor method init initialized the object. 39

OOP IMPLEMENTATION: INSTANTIATION AND INITIALIZATION We write a function init_instance that allows us to easily instantiate and initialize objects. def init_instance(cls, *args): instance = make_instance(cls) init = cls[ get ]( init ) if init is not None: init(instance, *args) return instance Make an instance of the class. Find the constructor method. If the constructor exists...... use it to initialize the object. Return the new instance. 40

OOP IMPLEMENTATION: INSTANTIATION AND INITIALIZATION We write a function init_instance that allows us to easily instantiate and initialize objects. def init_instance(cls, *args): instance = make_instance(cls) init = cls[ get ]( init ) if init is not None: The constructor name is fixed here. init(instance, *args) return instance 41

OOP IMPLEMENTATION: INSTANTIATION AND INITIALIZATION We add an extra message that our classes can understand, which will allow us to create new objects: def make_class(attributes={}, base_class=none):... def new(*args): return init_instance(cls, *args) cls = { get : get_value, set : set_value, new : new} return cls 42

OOP IMPLEMENTATION: USAGE def make_pokemon_class(): def init (self, name, owner, hp): self[ set ]( name, name) self[ set ]( owner, owner) self[ set ]( hp, hp) def increase_hp(self, amount): old_hp = self[ get ]( hp ) self[ set ]( hp, old_hp + amount)... return make_class({ init : init, increase_hp : increase_hp,...}) 43

OOP IMPLEMENTATION: USAGE >>> Pokemon = make_pokemon_class() >>> ashs_pikachu = Pokemon[ new ]( Pikachu, Ash, 300) >>> ashs_pikachu[ get ]( hp ) 300 >>> ashs_pikachu[ get ]( owner ) Ash >>> ashs_pikachu[ get ]( increase_hp )(50) >>> ashs_pikachu[ get ]( hp ) 350 44

CONCLUSION Today, after five weeks of studying two major programming paradigms, we designed an OOP system from scratch using only dictionaries and functions! Main idea: Classes and objects are dispatch dictionaries, which are passed messages, and which run code and assign (or update) variables as needed. 45