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

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

CS61A Lecture 16 Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 16, 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 20 Object Oriented Programming: Implementation. Jom Magrotker UC Berkeley EECS July 23, 2012

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

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

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

Programming with Python

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

Python Tutorial. Day 1

Positional, keyword and default arguments

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

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

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

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

Functions #5. Serdar ARITAN. Department of Computer Graphics Hacettepe University, Ankara, Turkey

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

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

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

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

Lecture 21. Programming with Subclasses

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

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

Software Development Python (Part B)

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

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

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

I/O Files. Chapter 10

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

Lecture 18. Classes and Types

CSC148H Week 1 >> COURSE INFORMATION, RECAP, OOP. Sadia Rain Sharmin Week of May 7, 2018

OBJECT ORIENTED PROGRAMMING 5

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

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

Lecture 21. Programming with Subclasses

All-Singing All-Dancing Python Bytecode Larry Hastings EuroPython 2013 July 2, 2013

Python Objects. Charles Severance. Python for Everybody

INHERITANCE AND NONLOCAL 6

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

Lecture 20. Subclasses & Inheritance

INHERITANCE AND INTERFACES 7

Lecture 21. Programming with Subclasses

Effective Programming Practices for Economists

Introduction to Python

Announcements for this Lecture

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

Object Oriented Programming

CSE : Python Programming

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

CMSC201 Computer Science I for Majors

61A Lecture 16. Wednesday, October 5

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

Spring 2018 Discussion 5: February 28, Object Oriented Programming

Python - 2. Jim Eng

IPSL python tutorial: some exercises for beginners

Programming environments. Introduction to Python. Adrian Copie, Ph.D.

Lecture 19. Operators and Abstraction

Computational Concepts Toolbox. Object Oriented Programming. Today: class. Review: Objects

CIS192 Python Programming. Robert Rand. August 27, 2015

Review 2. Classes and Subclasses

JAVA MOCK TEST JAVA MOCK TEST II

String Representations

Python for Finance. Advanced Features. Andras Niedermayer

CS1210 Lecture 28 Mar. 27, 2019

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

Lecture #12: Quick: Exceptions and SQL

Geophysics 501. Computa3onal Methods for the Geosciences. Flow Control and Lists. Zach Zens

What We ll Be Seeing Today

OBJECT ORIENTED PROGRAMMING

Lecture 9. Memory and Call Stacks

CIS192: Python Programming

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

CIS192 Python Programming

MITOCW watch?v=flgjisf3l78

Lecture 7. Memory in Python

The Pyth Language. Administrivia

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

Introduction to Python

Fundamentals of Programming. Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014

CIS192 Python Programming

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

Homework notes. Homework 2 grades posted on canvas. Homework 3 due tomorrow. Homework 4 posted on canvas. Due Tuesday, Oct. 3

PYTHON CONTENT NOTE: Almost every task is explained with an example

CS 2316 Exam 1 Spring 2014

CSC102 INTRO TO PROGRAMMING WITH PYTHON REVIEW MICHAEL GROSSBERG

a declaration of class name, and a class docstring

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

Python in 10 (50) minutes

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

CSI33 Data Structures

Sorting HOW TO Release 2.7.6

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

CS 11 python track: lecture 3. n Today: Useful coding idioms

Algorithms for Bioinformatics

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

Exam #3, Form 3 A CSE 231 Fall 2015 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Beyond Blocks: Python Session #1

Programming I. Course 9 Introduction to programming

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Transcription:

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 images into music helps individualswithout vision reach for objects in space/ 2

Review: Inheritance Polymorphism Mutable Lists TODAY 3

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. 4

REVIEW: INHERITANCE Occasionally, we find that many abstract data types are related. For example, there are many different kinds of people, but all of them have similar methods of eating and sleeping. 5

REVIEW: INHERITANCE We would like to have different kinds of Pokémon, besides the Normal Pokemon (like Togepi) which differ (among other things) in the amount of points lost by its opponent during an attack. The only method that changes is attack. All the other methods remain the same. Can we avoid duplicating code for each of the different kinds? 6

REVIEW: INHERITANCE Key OOP Idea: Classes can inherit methods and instance variables from other classes. class WaterPokemon(Pokemon): def attack(self, other): other.decrease_hp(75) class ElectricPokemon(Pokemon): def attack(self, other): other.decrease_hp(60) 7

REVIEW: INHERITANCE Key OOP Idea: Classes can inherit methods and instance variables from other classes. class WaterPokemon(Pokemon): def attack(self, other): other.decrease_hp(75) class ElectricPokemon(Pokemon): def attack(self, other): other.decrease_hp(60) 8

REVIEW: INHERITANCE Key OOP Idea: Classes can inherit methods and instance variables from other classes. class WaterPokemon(Pokemon): def attack(self, other): other.decrease_hp(75) class ElectricPokemon(Pokemon): def attack(self, other): other.decrease_hp(60) 9

REVIEW: INHERITANCE >>> ashs_squirtle = WaterPokemon( Squirtle, Ash, 314) >>> mistys_togepi = Pokemon( Togepi, Misty, 245) >>> mistys_togepi.attack(ashs_squirtle) >>> ashs_squirtle.get_hit_pts() 264 >>> ashs_squirtle.attack(mistys_togepi) >>> mistys_togepi.get_hit_pts() 170 10

REVIEW: INHERITANCE >>> ashs_squirtle = WaterPokemon( Squirtle, Ash, 314) >>> mistys_togepi = Pokemon( Togepi, Misty, 245) >>> mistys_togepi.attack(ashs_squirtle) >>> ashs_squirtle.get_hit_pts() 264 >>> ashs_squirtle.attack(mistys_togepi) >>> mistys_togepi.get_hit_pts() 170 mistys_togepi uses the attack method from the Pokemon class. 11

REVIEW: INHERITANCE >>> ashs_squirtle = WaterPokemon( Squirtle, Ash, 314) >>> mistys_togepi = Pokemon( Togepi, Misty, 245) >>> mistys_togepi.attack(ashs_squirtle) >>> ashs_squirtle.get_hit_pts() 264 >>> ashs_squirtle.attack(mistys_togepi) >>> mistys_togepi.get_hit_pts() 170 ashs_squirtle uses the attack method from the WaterPokemon class. 12

REVIEW: INHERITANCE >>> ashs_squirtle = WaterPokemon( Squirtle, Ash, 314) >>> mistys_togepi = Pokemon( Togepi, Misty, 245) >>> mistys_togepi.attack(ashs_squirtle) >>> ashs_squirtle.get_hit_pts() 264 >>> ashs_squirtle.attack(mistys_togepi) >>> mistys_togepi.get_hit_pts() 170 13

REVIEW: INHERITANCE If the class of an object has the method or attribute of interest, that particular method or attribute is used. Otherwise, the method or attribute of its parent is used. Inheritance can be many levels deep. If the parent class does not have the method or attribute, we check the parent of the parent class, and so on. 14

REVIEW: INHERITANCE We can also both override a parent s method or attribute and use the original parent s method. Say that we want to modify the attacks of Electric Pokémon: when they attack another Pokémon, the other Pokémon loses the original 50 HP, but the Electric Pokémon gets an increase of 10 HP. 15

REVIEW: INHERITANCE class ElectricPokemon(Pokemon):... def attack(self, other): Pokemon.attack(self, other) self.increase_hp(10) 16

PROPERTIES Python allows us to create attributes that are computed from other attributes, but need not necessarily be instance variables. Say we want each Pokemon object to say its complete name, constructed from its owner s name and its own name. 17

PROPERTIES One way is to define a new method. class Pokemon:... def complete_name(self): return self.owner + s + self.name >>> ashs_pikachu.complete_name() Ash s Pikachu 18

PROPERTIES Another way is to use the property decorator. class Pokemon:... @property def complete_name(self): return self.owner + s + self.name >>> ashs_pikachu.complete_name Ash s Pikachu 19

ANNOUNCEMENTS Project 2 is due Friday, July 13. Homework 7 is due Saturday, July 14. Project 3 will be released this weekend, due Tuesday, July 24. Your TA will distribute your graded midterms in exchange for a completed survey. 20

WHAT IS YOUR TYPE? OOP enables us to easily make new abstract data types for different types of data. >>> type(ashs_pikachu) <class ElectricPokemon > >>> type(ashs_squirtle) <class WaterPokemon > >>> type(mistys_togepi) is Pokemon True 21

POLYMORPHISM Write the method attack_all for the Pokemon class that takes a tuple of Pokemon objects as its argument. When called on a Pokemon object, that Pokémon will attack each of the Pokémon in the provided tuple. (Ignore the output printed by the attack method.) >>> ashs_pikachu = ElectricPokemon( Pikachu, Ash, 300) >>> ashs_squirtle = WaterPokemon( Squirtle, Ash, 314) >>> mistys_togepi = Pokemon( Togepi, Misty, 245) >>> mistys_togepi.attack_all((ashs_pikachu, ashs_squirtle)) >>> ashs_pikachu.get_hit_pts() 250 >>> ashs_squirtle.get_hit_pts() 264 22

POLYMORPHISM class Pokemon:... def attack_all(self, others): for other in others: self.attack(other) 23

POLYMORPHISM for other in others: self.attack(other) other can be an object of many different data types: ElectricPokemon, WaterPokemon, and Pokemon, for example. 24

POLYMORPHISM for other in others: self.attack(other) attack can work on objects of many different data types, without having to consider each data type separately. attack is polymorphic. 25

POLYMORPHISM Write the method attacked_by for the Pokemon class that takes a tuple of Pokemon objects as its argument. When called on a Pokemon object, that Pokémon will be attacked by each of the Pokémon in the provided tuple. >>> ashs_pikachu = ElectricPokemon( Pikachu, Ash, 300) >>> ashs_squirtle = WaterPokemon( Squirtle, Ash, 314) >>> mistys_togepi = Pokemon( Togepi, Misty, 245) >>> ashs_squirtle.attacked_by((ashs_pikachu, mistys_togepi)) >>> ashs_squirtle.get_hit_pts() 204 26

POLYMORPHISM class Pokemon:... def attacked_by(self, others): for other in others: other.attack(self) 27

POLYMORPHISM for other in others: other.attack(self) other can be an object of many different data types: ElectricPokemon, WaterPokemon, and Pokemon, for example. It can also be an object of any other class that has an attack method. 28

POLYMORPHISM Key OOP idea: The same method can work on data of different types. We have seen a polymorphic function before: >>> 3 + 4 7 >>> hello + world hello world 29

POLYMORPHISM: HOW DOES + WORK? We try the type function on other expressions: >>> type(9001) <class int > >>> type( hello world ) <class str > >>> type(3.0) <class float > http://diaryofamadgayman.files.wordpress.com/2012/01/wait what.jpg 30

POLYMORPHISM: HOW DOES + WORK? Everything (even numbers and strings) in Python is an object. In particular, every class (int, str, Pokemon,...) is a subclass of a built in object class. 31

EVERYTHING IS AN OBJECT The dir function shows the attributes of a class: >>> dir(waterpokemon) [' class ', ' delattr ', ' dict ',..., 'attack', 'decrease_hp', 'get_hit_pts', 'get_name', 'get_owner', 'increase_hp', 'total_pokemon'] The green attributes were defined inside (and inherited from) the Pokemon class and the blue attribute was defined directly inside the WaterPokemon class. Where did the red attributes come from? 32

EVERYTHING IS AN OBJECT The object class provides extra attributes that enable polymorphic operators like + to work on many different forms of data. >>> dir(object) [' class ', ' delattr ', ' doc ', ' eq ', ' format ', ' ge ', ' getattribute ', ' gt ', ' hash ', ' init ', ' le ', ' lt ', ' ne ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ', ' sizeof ', ' str ', ' subclasshook '] 33

EVERYTHING IS AN OBJECT Since everything is an object, this means we should be able to call methods on everything, including numbers: >>> 3 + 4 7 >>> (3). add (4) 7 34

EVERYTHING IS AN OBJECT Python converts the expression 3 + 4 to (3). add (4) 3 is an int object. The int class has an add method. 35

EVERYTHING IS AN OBJECT Python converts the expression hello + world to ( hello ). add ( world ) hello is a str object. The str class also has a different add method. 36

EVERYTHING IS AN OBJECT If a class has an add method, we can use the + operator on two objects of the class. Similarly, for example, 4 > 3 is converted to (4). gt (3) 4 <= 3 is converted to (4). le (3) 4 == 3 is converted to (4). eq (3) (4). str () produces the string representation of 4 (used in printing, for example). 37

EVERYTHING IS AN OBJECT Implement the method gt for the Pokemon class that will allow us to check if one Pokémon is greater than another, which means that it has (strictly) more HP than the other. >>> ashs_pikachu = ElectricPokemon( Pikachu, Ash, 300) >>> ashs_squirtle = WaterPokemon( Squirtle, Ash, 314) >>> ashs_pikachu > ashs_squirtle False 38

EVERYTHING IS AN OBJECT Implement the method gt for the Pokemon class that will allow us to check if one Pokémon is greater than another, which means that it has (strictly) more HP than the other. class Pokemon:... def gt (self, other): return 39

EVERYTHING IS AN OBJECT Implement the method gt for the Pokemon class that will allow us to check if one Pokémon is greater than another, which means that it has (strictly) more HP than the other. class Pokemon:... def gt (self, other): return self.get_hit_pts() > other.get_hit_pts() 40

EVERYTHING IS AN OBJECT The object class provides a default gt method, but the gt method we defined for the Pokemon class overrides the method provided by the object class, as we would expect from inheritance. Bottom line: Inheritance and polymorphism in Python OOP allow us to override standard operators! 41

EVERYTHING IS AN OBJECT Side note: Every class inherits from the object class, including the Pokemon class. class Pokemon: is shorthand for class Pokemon(object): Both are equivalent and correct. 42

VIDEO BREAK http://www.youtube.com/watch?v=d1tn56vwu_g 43

MUTABLE DATA STRUCTURES We have seen that objects possess state: they can change over time. Objects are thus mutable. The IRLists and IDicts we saw earlier were immutable, which means that once created, they could not be modified. Python has built in list and dictionary data structures that are mutable. 44

PYTHON LISTS: A PRIMER >>> a = [3, 4, 5] >>> a[0] 3 >>> a[1:] [4, 5] >>> a[0] = 7 >>> a [7, 4, 5] 45

PYTHON LISTS: A PRIMER >>> a [7, 4, 5] >>> a.append(10) >>> a [7, 4, 5, 10] >>> a.extend([2, 3]) >>> a [7, 4, 5, 10, 2, 3] >>> a[2:4] = [6, 8] [7, 4, 6, 8, 2, 3] >>> a.pop() 3 >>> a [7, 4, 6, 8, 2] >>> a.remove(8) [7, 4, 6, 2] None of these operations create new lists. They all update the same list. 46

PYTHON LISTS: LIST COMPREHENSIONS List comprehensions allow us to create new lists in the style of generator expressions. >>> a = [2, 4, 6] >>> b = [2*item for item in a] >>> b [4, 8, 12] 3. Add twice the element to the new list. 2. Call each element item. 1. Take the list a. 47

PYTHON LISTS: LIST COMPREHENSIONS List comprehensions allow us to create new lists in the style of generator expressions. >>> a = [2, 4, 6] >>> b = [2*item for item in a if item > 3] >>> b [8, 12] 3. Add twice the element to the new list 2. Call each element item. 1. Take the list a. 4. but only if item is greater than 3. 48

CONCLUSION Inheritance and polymorphism are two key ideas in OOP. Inheritance allows us to establishes relationships (and reuse code) between two similar data types. Polymorphism allows functions to work on many types of data. Everything in Python is an object. Python OOP allows us to override standard operators. Python has built in mutable lists. Preview: More about lists and dictionaries. 49