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

Slides:



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

Python Objects and Classes
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
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.
Classes 2 COMPSCI 105 SS 2015 Principles of Computer Science.
Dictionaries: Keeping track of pairs
Rapid GUI Programming with Python and Qt Classes and Modules By Raed S. Rasheed Classes and Modules By Raed S. Rasheed 1.
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
Fundamentals of Programming II Inheritance and Abstract Classes
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
1 Python Chapter 3 Reading strings and printing. © Samuel Marateck.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012.
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
Methods in Computational Linguistics II Queens College Lecture 7: Structuring Things.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
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.
Chapter 11 Introduction to Classes. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. Code Listing 11.1.
1 CS 177 Week 16 Recitation Recursion. 2 Objective To understand and be able to program recursively by breaking down a problem into sub problems and joining.
CS61A Lecture 22 Interpretation Jom Magrotker UC Berkeley EECS July 25, 2012.
CS61A Lecture 13 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 10, 2012.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Chapter 8 More On Functions. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. First cut, scope.
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.
ICAPRG301A Week 2 Strings and things Charles Babbage Developed the design for the first computer which he called a difference engine, though.
Python Overview  Last week Python 3000 was released  Python 3000 == Python 3.0 == Py3k  Designed to break backwards compatibility with the 2.x.
CS61A Lecture 23 Py Jom Magrotker UC Berkeley EECS July 26, 2012.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
CSCI-383 Object-Oriented Programming & Design Lecture 10.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
CS61A Lecture 27 Logic Programming Jom Magrotker UC Berkeley EECS August 2, 2012.
Object-Oriented Programming Chapter Chapter
Object Oriented Programing (OOP)
OOP with Objective-C Categories, Protocols and Declared Properties.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 12 Inheritance and Class Design 1.
CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.
Lecture 09 – Classes.  At the end of this lecture, students should be able to:  Define a new class  Store state information about instances of the.
CIT 590 Intro to Programming Lecture 4. How are assignments evaluated Pay attention to what the HW says it is trying to teach you about ‘modular programming’
Basic Concepts of OOP.  Object-Oriented Programming (OOP) is a type of programming added to php5 that makes building complex, modular and reusable web.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
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.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
CSCE 240 – Intro to Software Engineering Lecture 3.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Python 3000.
COMPSCI 107 Computer Science Fundamentals
CS-104 Final Exam Review Victor Norman.
Copyright (c) 2017 by Dr. E. Horvath
Object Oriented Programming in Python
Week 6 Object-Oriented Programming (2): Polymorphism
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Introduction to Object-Oriented Programming (OOP)
Presentation transcript:

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

2 C OMPUTER S CIENCE IN THE N EWS without-vision-reach-for-objects-in-space/

3 T ODAY Review: Inheritance Polymorphism Mutable Lists

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

5 R EVIEW : I NHERITANCE 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.

6 R EVIEW : I NHERITANCE 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?

7 R EVIEW : I NHERITANCE 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 R EVIEW : I NHERITANCE 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) The Pokemon class is the superclass (or parent class) of the WaterPokemon class. The WaterPokemon class is the subclass (or child class) of the Pokemon class.

9 R EVIEW : I NHERITANCE 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) The attack method from the Pokemon class is overridden by the attack method from the WaterPokemon class.

10 R EVIEW : I NHERITANCE >>> 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

11 R EVIEW : I NHERITANCE >>> 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.

12 R EVIEW : I NHERITANCE >>> 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.

13 R EVIEW : I NHERITANCE >>> 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 The WaterPokemon class does not have a get_hit_pts method, so it uses the method from its superclass.

14 R EVIEW : I NHERITANCE 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.

15 R EVIEW : I NHERITANCE 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.

16 R EVIEW : I NHERITANCE class ElectricPokemon(Pokemon):... def attack(self, other): Pokemon.attack(self, other) self.increase_hp(10) We use the original attack method from the parent.

17 P ROPERTIES 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.

18 P ROPERTIES 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’ However, this seems like it should be an attribute (something the data is), instead of a method (something the data can do).

19 P ROPERTIES Another way is to use the property decorator. class def complete_name(self): return self.owner + “’s ” + self.name >>> ashs_pikachu.complete_name ‘Ash’s Pikachu’ A new attribute is calculated!

20 A NNOUNCEMENTS 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.

21 W HAT IS Y OUR T YPE ? OOP enables us to easily make new abstract data types for different types of data. >>> type(ashs_pikachu) >>> type(ashs_squirtle) >>> type(mistys_togepi) is Pokemon True The type function displays the type of its argument.

22 P OLYMORPHISM 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

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

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

25 P OLYMORPHISM 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. poly = Many morph = Forms poly = Many morph = Forms

26 P OLYMORPHISM 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

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

28 P OLYMORPHISM 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.

29 P OLYMORPHISM Key OOP idea: The same method can work on data of different types. We have seen a polymorphic function before: >>> >>> ‘hello’ + ‘ world’ ‘hello world’ The + operator, or the add function, is polymorphic. It can work with both numbers and strings.

30 P OLYMORPHISM : H OW D OES + W ORK ? We try the type function on other expressions: >>> type(9001) >>> type(‘hello world’) >>> type(3.0) W AIT ! Are these objects of different classes? W AIT ! Are these objects of different classes?

31 P OLYMORPHISM : H OW D OES + W ORK ? 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. Not true for many other languages. This is not the term ‘object’, but a class whose name is object.

32 E VERYTHING IS AN O BJECT 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?

33 E VERYTHING IS AN O BJECT 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__'] We will consider a few of these. The rest, we leave to your experiments.

34 E VERYTHING IS AN O BJECT Since everything is an object, this means we should be able to call methods on everything, including numbers: >>> >>> (3).__add__(4) 7

35 E VERYTHING IS AN O BJECT Python converts the expression to (3).__add__(4) 3 is an int object. The int class has an __add__ method. The conversion is slightly more complicated than this, but the basic idea is the same.

36 E VERYTHING IS AN O BJECT Python converts the expression ‘hello’ + ‘ world’ to (‘hello’).__add__(‘ world’) ‘hello’ is a str object. The str class also has a different __add__ method.

37 E VERYTHING IS AN O BJECT 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).

38 E VERYTHING IS AN O BJECT 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

39 E VERYTHING IS AN O BJECT 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 ________________________________________

40 E VERYTHING IS AN O BJECT 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()

41 E VERYTHING IS AN O BJECT 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!

42 E VERYTHING IS AN O BJECT 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.

43 V IDEO B REAK

44 M UTABLE D ATA S TRUCTURES 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.

45 P YTHON L ISTS : A P RIMER >>> a = [3, 4, 5] >>> a[0] 3 >>> a[1:] [4, 5] >>> a[0] = 7 >>> a [7, 4, 5] Could not have done this with tuples! Slicing makes a new list.

46 P YTHON L ISTS : A P RIMER >>> 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. The slicing operator here does not make a new list. It refers to elements and positions in the original list.

47 P YTHON L ISTS : L IST C OMPREHENSIONS 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] 1. Take the list a. 2. Call each element item. 3. Add twice the element to the new list.

48 P YTHON L ISTS : L IST C OMPREHENSIONS 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] 1. Take the list a. 2. Call each element item. 3. Add twice the element to the new list… 4. … but only if item is greater than 3.

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