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

Slides:



Advertisements
Similar presentations
CS61A Lecture 25 Delayed Sequences Jom Magrotker UC Berkeley EECS July 31, 2012.
Advertisements

Python Objects and Classes
CIT 590 Intro to Programming Classes. Schedule change The upcoming HW (HW6) is your last major Python HW. It will involve object oriented programming.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 28 Classes and Methods 6/17/09 Python Mini-Course: Lesson 28 1.
CS61A Lecture 8 Data Abstraction Tom Magrino and Jon Kotker UC Berkeley EECS June 28, 2012.
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
CS61A Lecture 4 Higher Order Functions Tom Magrino and Jon Kotker UC Berkeley EECS June 21, 2012.
Programming with Alice Computing Institute for K-12 Teachers Summer 2011 Workshop.
H OW O BJECTS B EHAVE. O VERVIEW Methods use object state Arguments and return types in methods Java passes by value Getters and Setters Encapsulation.
Road Map Introduction to object oriented programming. Classes
CS 106 Introduction to Computer Science I 03 / 23 / 2007 Instructor: Michael Eckmann.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Guide to Programming with Python
CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CIT 590 Intro to Programming Style Classes. Remember to finish up findAllCISCourses.py.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
CSC 212 – Data Structures Lecture 12: Java Review.
CS61A Lecture 21 Scheme Jom Magrotker UC Berkeley EECS July 24, 2012.
CS61A Lecture 16 Mutable Data Structures Jom Magrotker UC Berkeley EECS July 16, 2012.
Fall Week 3 CSCI-141 Scott C. Johnson.  Say we want to draw the following figure ◦ How would we go about doing this?
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
CS61A Lecture 22 Interpretation Jom Magrotker UC Berkeley EECS July 25, 2012.
CS61A Lecture 6 Recursion Tom Magrino and Jon Kotker UC Berkeley EECS June 26, 2012.
Trees! =) Write up-add tree which behaves in this manner: 1 31 / \ / \ 3 5  21 9 / | \ \ / | \ \
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012.
Objects & Dynamic Dispatch CSE 413 Autumn Plan We’ve learned a great deal about functional and object-oriented programming Now,  Look at semantics.
Topics: Function Intitution Algorithm Example Function Definition (and Indentation) Function Call Naming and Binding Local Variables Function Arguments.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CSCI-383 Object-Oriented Programming & Design Lecture 18.
CS61A Lecture 23 Py Jom Magrotker UC Berkeley EECS July 26, 2012.
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.
1 Chapter Four Creating and Using Classes. 2 Objectives Learn about class concepts How to create a class from which objects can be instantiated Learn.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
CS61A Lecture 27 Logic Programming Jom Magrotker UC Berkeley EECS August 2, 2012.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Object-Oriented Programming Chapter Chapter
Object Oriented Programing (OOP)
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.
Written by: Dr. JJ Shepherd
Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
CS61A Lecture 10 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 3, 2012.
CS61A Lecture 11 Immutable Trees Jom Magrotker UC Berkeley EECS July 5, 2012.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Spring 2016.
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Winter 2013.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Spring 2017.
CS-104 Final Exam Review Victor Norman.
Object-Oriented Programming & Design Lecture 14 Martin van Bommel
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Autumn 2017.
Engineering Computing
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Autumn 2018.
Recursion 2-Dec-18.
Recursion 29-Dec-18.
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Zach Tatlock Winter 2018.
CISC/CMPE320 - Prof. McLeod
*Lecture based on notes from SICP
CSE341: Programming Languages Lecture 21 Dynamic Dispatch Precisely, and Manually in Racket Dan Grossman Spring 2019.
Presentation transcript:

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

2 C OMPUTER S CIENCE IN THE N EWS

3 C OMPUTER S CIENCE IN THE N EWS

4 T ODAY Review: Dispatch Functions Dispatch Dictionaries OOP Implementation

5 R EVIEW : D ISPATCH F UNCTIONS We saw that we do not need data structures to store information: we can use functions to accomplish the storage and retrieval of data.

6 R EVIEW : D ISPATCH F UNCTIONS 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

7 R EVIEW : D ISPATCH F UNCTIONS 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.

8 M ESSAGE P ASSING 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?

9 D ISPATCH D ICTIONARIES 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.

10 D ISPATCH D ICTIONARIES def make_pair(first, second): pair_dict = { ‘first’ : first, ‘second’: second } return pair_dict How do we create and use “pair objects” now?

11 D ISPATCH D ICTIONARIES >>> def make_pair(first, second):... >>> p = make_pair(1, 2) G make_pair params: (first, second) body: pair_dict = {... } E1 first1 second2 ‘first’1 ‘second’2 p pair_dict

12 D ISPATCH D ICTIONARIES >>> p[‘first’] 1 G make_pair params: (first, second) body: pair_dict = {... } E1 first1 second2 ‘first’1 ‘second’2 p pair_dict

13 D ISPATCH D ICTIONARIES >>> p[‘first’] = 3 G make_pair params: (first, second) body: pair_dict = {... } E1 first1 second2 ‘first’1 ‘second’2 p 3 pair_dict

14 A NNOUNCEMENTS : M IDTERM 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.

15 A NNOUNCEMENTS 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!

16 OOP I MPLEMENTATION : P REFACE 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.

17 OOP I MPLEMENTATION : P REFACE Things we will implement: Classes and objects Class variables Instance variables Methods Inheritance

18 OOP I MPLEMENTATION : P REFACE 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?)

19 OOP I MPLEMENTATION 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.

20 OOP I MPLEMENTATION 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.

21 OOP I MPLEMENTATION : C LASS V ARIABLES First solution: def make_class(attributes={}, base_class=None): return attributes def make_pokemon_class(): return make_class({‘total_pokemon’: 0}) Dictionary of class variables

22 OOP I MPLEMENTATION : C LASS V ARIABLES 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

23 OOP I MPLEMENTATION : I NHERITANCE 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.

24 OOP I MPLEMENTATION : I NHERITANCE 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.

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

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

27 OOP I MPLEMENTATION : I NHERITANCE 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.

28 OOP I MPLEMENTATION : I NHERITANCE 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

29 OOP I MPLEMENTATION : O BJECTS 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 attributes = {} instance = {‘get’: get_value, ‘set’: set_value} return instance 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 An instance is a dictionary! The two messages get and set allow us to use the general getter and setter functions. What class is this object an instance of?

30 OOP I MPLEMENTATION : O BJECTS 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 attributes = {} instance = {‘get’: get_value, ‘set’: set_value} return instance Every instance gets its own dictionary of instance attributes.

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

32 B REAK

33 R EVIEW : B OUND M ETHODS A method is bound to an instance. Pokemon.increase_hp(ashs_pikachu, 150) is equivalent to ashs_pikachu.increase_hp(150) Use the increase_hp method defined for objects of the Pokemon class… … with self being the ashs_pikachu object … … and amount being 150. Use the increase_hp method of (or bound to) the ashs_pikachu object… … with amount being 150. “of”

34 B OUND M ETHODS 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.

35 B OUND M ETHODS 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) Notice that we do not need to provide the first argument anymore! a is bound to 5. Notice that we do not need to provide the first argument anymore! a is bound to 5.

36 OOP I MPLEMENTATION : L OOKING A HEAD 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):... These self arguments need to be bound to the object on which the method is called.

37 OOP I MPLEMENTATION : O BJECTS 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) All the methods are defined in the class. We might get one of these: if we do, bind the first argument to the current instance to produce a bound method for the instance.

38 OOP I MPLEMENTATION : O BJECTS def bind_method(value, instance): if callable(value): def method(*args): return value(instance, *args) return method else: 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. callable is a predicate that checks if the argument provided can be called with arguments.

39 OOP I MPLEMENTATION : I NSTANTIATION AND I NITIALIZATION 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.

40 OOP I MPLEMENTATION : I NSTANTIATION AND I NITIALIZATION 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.

41 OOP I MPLEMENTATION : I NSTANTIATION AND I NITIALIZATION 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 The constructor name is fixed here.

42 OOP I MPLEMENTATION : I NSTANTIATION AND I NITIALIZATION 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

43 OOP I MPLEMENTATION : U SAGE 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,...})

44 OOP I MPLEMENTATION : U SAGE >>> 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

45 C ONCLUSION 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.