CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 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
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 and Inheritance. 2 As the building blocks of more complex systems, objects can be designed to interact with each other in one of three ways: Association:
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
Object-Oriented PHP (1)
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Starting Classes and Methods. Objects have behaviors In old style programming, you had: –data, which was completely passive –functions, which could manipulate.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
1 Basic Object-Oriented Concepts  Object-Oriented Paradigm What is an Object?  What is a Class?  Constructing Objects from a class Problem Solving in.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
6 April, 2000 CS1001 Lecture 15 EXAM1 - results SUBPROGRAM - - revisit FUNCTION.
Guide to Programming with Python
CS61A Lecture 3 Higher Order Functions Jon Kotker and Tom Magrino UC Berkeley EECS June 20, 2012.
Fortran- Subprograms Chapters 6, 7 in your Fortran book.
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.
GENERAL CONCEPTS OF OOPS INTRODUCTION With rapidly changing world and highly competitive and versatile nature of industry, the operations are becoming.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
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.
CS61A Lecture 15 Object-Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012.
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.
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.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
CS61A Lecture 12 Immutable Trees Jom Magrotker UC Berkeley EECS July 9, 2012.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
CS61A Lecture 23 Py Jom Magrotker UC Berkeley EECS July 26, 2012.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
CSCI-383 Object-Oriented Programming & Design Lecture 10.
CS61A Lecture 27 Logic Programming Jom Magrotker UC Berkeley EECS August 2, 2012.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Object Oriented Programing (OOP)
1 CS 177 Week 11 Recitation Slides Class Design/Custom Classes.
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
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.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
CS61A Lecture 20 Object-Oriented Programming: Implementation Jom Magrotker UC Berkeley EECS July 23, 2012.
Section 6.1 CS 106 Victor Norman IQ Unknown. The Big Q What do we get by being able to define a class?! Or Do we really need this?!
OOP: Inheritance. Inheritance A class can extend another class, inheriting all its data members and methods while redefining some of them and/or adding.
Testing CSE 160 University of Washington 1. Testing Programming to analyze data is powerful It’s useless (or worse!) if the results are not correct Correctness.
CS61A Lecture 9 Immutable Data Structures Jom Magrotker UC Berkeley EECS July 2, 2012.
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
Algorithms and Pseudocode
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.
CS61A Lecture 29 Parallel Computing Jom Magrotker UC Berkeley EECS August 7, 2012.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
Object-oriented programming (OOP) is a programming paradigm using "objects" – data structures consisting of data fields and methods together with their.
Static data members Constructors and Destructors
CS-104 Final Exam Review Victor Norman.
Lecture VI Objects The OOP Concept Defining Classes Methods
Creating and Deleting Instances Access to Attributes and Methods
Loops CIS 40 – Introduction to Programming in Python
An Introduction to Object Orientated Programming
Object Oriented Programming in A Level
REPETITION Why Repetition?
Presentation transcript:

CS61A Lecture 14 Object-Oriented Programming Jom Magrotker UC Berkeley EECS July 11, 2012

2 C OMPUTER S CIENCE IN THE N EWS

3 T ODAY Review: Object-Oriented Programming Inheritance

4 W HERE W E W ERE : F UNCTIONAL P ROGRAMMING One of many programming paradigms where functions are the central players. Functions can work on data, which can sometimes be other functions. Style of programming

5 W HERE W E W ERE : F UNCTIONAL P ROGRAMMING Key Feature: Composition Functions can receive input from, and provide output to, other functions. Many problems can be solved by “chaining” the outputs of one function to the inputs of the next.

6 W HERE W E W ERE : F UNCTIONAL P ROGRAMMING Key Feature: Composition Example: Sum of all prime numbers from 2 to 100. reduce(add, filter(lambda num: is_prime(num), range(2, 101)), 0) 1. Generate all the numbers from 2 to Filter out the prime numbers. 3. Sum the prime numbers up.

7 W HERE W E W ERE : F UNCTIONAL P ROGRAMMING Key Feature: Statelessness Functions always produce the same outputs for the same inputs. This makes them incredibly useful for, for example, processing a lot of data in parallel.

8 W HERE W E W ERE : F UNCTIONAL P ROGRAMMING Key Feature: Statelessness Because of statelessness, if we need to update a piece of data, we need to create a whole new piece of data. my_idict = idict_insert(my_idict, ‘a’, 5) 1. Take an IDict. 2. Insert the new item. 3. Get a new IDict. 4. Store the new IDict.

9 W HERE W E W ERE : F UNCTIONAL P ROGRAMMING Key Feature: Statelessness Functional programming is clunky for data that changes over time, or that has state. We need an easier way to work with stateful data.

10 O BJECT -O RIENTED P ROGRAMMING A new programming paradigm where objects are the central players. Objects are data structures that are combined with associated behaviors. They are “smart bags” of data that have state and can interact. Functions can do one thing; objects can do many related things. Hence the term “object-oriented”.

11 T ERMINOLOGY Any person is a human. A single person has a name and age. O BJECT C LASS I NSTANCE of the Human class I NSTANCE V ARIABLES

12 T ERMINOLOGY An object is an instance of a class. For example, a person is an instance of a human. The class describes its objects: it is a template.

13 T ERMINOLOGY Objects and instance variables have a “has-a” relationship. An instance variable is an attribute specific to an instance. An object has an instance variable.

14 T ERMINOLOGY A single person can eat and sleep. The population of the Earth is 7 billion. M ETHODS C LASS V ARIABLES

15 T ERMINOLOGY Objects have certain behaviors, known as methods. There are attributes for the class as a whole, not for specific instances: these are class variables.

16 A NNOUNCEMENTS : M IDTERM 1 Grades are available through glookup. Mean: 38.0, standard deviation: 8.6. Your TA will distribute the graded midterms in lab today, in exchange for a completed survey. The average of the class improved by 1 point when scores on the group portion were considered. Midterm solutions will be released soon. Post-midterm destress potluck tonight from 6:30pm to 10pm in the Wozniak lounge (4 th floor Soda).

17 OOP IN P YTHON class Pokemon: __total_pokemon = 0 def __init__(self, name, owner, hit_pts): self.__name = name self.__owner = owner self.__hp = hit_pts Pokemon.__total_pokemon += 1 C LASS C LASS V ARIABLE I NSTANCE V ARIABLES

18 OOP IN P YTHON class Pokemon: __total_pokemon = 0 def __init__(self, name, owner, hit_pts): self.__name = name self.__owner = owner self.__hp = hit_pts Pokemon.__total_pokemon += 1 C ONSTRUCTOR self refers to the I NSTANCE. Class variables are referenced using the name of the class, since they do not belong to a specific instance.

19 OOP IN P YTHON class Pokemon: __total_pokemon = 0 def __init__(self, name, owner, hit_pts): self.__name = name self.__owner = owner self.__hp = hit_pts Pokemon.__total_pokemon += 1 “of” Name of the instance ( self ) Total number of Pokémon

20 OOP IN P YTHON class Pokemon:... def increase_hp(self, amount): self.__hp += amount def decrease_hp(self, amount): self.__hp -= amount M ETHODS

21 OOP IN P YTHON class Pokemon:... def increase_hp(self, amount): self.__hp += amount def decrease_hp(self, amount): self.__hp -= amount Every method needs self as an argument.

22 OOP IN P YTHON class Pokemon:... def get_name(self): return self.__name def get_owner(self): return self.__owner def get_hit_pts(self): return self.__hp S ELECTORS

23 OOP IN P YTHON >>> ashs_pikachu = Pokemon(‘Pikachu’, ‘Ash’, 300) >>> mistys_togepi = Pokemon(‘Togepi’, ‘Misty’, 245) >>> mistys_togepi.get_owner() ‘Misty’ >>> ashs_pikachu.get_hit_pts() 300 >>> ashs_pikachu.increase_hp(150) >>> ashs_pikachu.get_hit_pts() 450 We now have state! The same expression evaluates to different values. We now have state! The same expression evaluates to different values.

24 OOP IN P YTHON The statement ashs_pikachu = Pokemon(‘Pikachu’, ‘Ash’, 300) instantiates a new object. The __init__ method (the constructor) is called by this statement. Objects can only be created by the constructor.

25 S MART B AGS OF D ATA ashs_pikachu = Pokemon(‘Pikachu’, ‘Ash’, 300) mistys_togepi = Pokemon(‘Togepi’, ‘Misty’, 245) The statements above create two new objects: Instance variables: __name __owner __hp Methods: increase_hp decrease_hp get_name get_owner get_hit_pts Instance variables: __name __owner __hp Methods: increase_hp decrease_hp get_name get_owner get_hit_pts

26 S MART B AGS OF D ATA Each object gets its own set of instance variables and bound methods. Each object is a “smart bag” of data: it has data and it can also manipulate the data. Instance variables: __name __owner __hp Methods: increase_hp decrease_hp get_name get_owner get_hit_pts Instance variables: __name __owner __hp Methods: increase_hp decrease_hp get_name get_owner get_hit_pts

27 B OUND M ETHODS A method is bound to an instance. Pokemon.increase_hp(ashs_pikachu, 150) evaluates to ashs_pikachu.increase_hp(150) self is implicitly the object itself.

28 O BJECT I DENTITY Every object has its own set of independent instance variables and bound methods. >>> ashs_pikachu = Pokemon(‘Pikachu’, ‘Ash’, 300) >>> brocks_pikachu = ashs_pikachu >>> brocks_pikachu is ashs_pikachu True >>> brocks_pikachu = Pokemon(‘Pikachu’, ‘Brock’, 300) >>> brocks_pikachu is ashs_pikachu False Assigning the same object to two different variables. The is operator checks if the two variables evaluate to the same object.

29 OOP IN P YTHON : P RACTICE Which methods in the Pokemon class should be modified to ensure that the HP never goes down below zero? How should it be modified? We modify the decrease_hp method: def decrease_hp(self, amount): self.__hp -= amount if self.__hp < 0: self.__hp = 0

30 OOP IN P YTHON : P RACTICE Write the method attack that takes another Pokemon object as an argument. When this method is called on a Pokemon object, the object screams (= prints) its name and reduces the HP of the opposing Pokémon by 50. >>> mistys_togepi.get_hp() 245 >>> ashs_pikachu.attack(mistys_togepi) Pikachu! >>> mistys_togepi.get_hp() 195

31 OOP IN P YTHON : P RACTICE Write the method attack that takes another Pokemon object as an argument. When this method is called on a Pokemon object, the object screams (= prints) its name and reduces the HP of the opposing Pokémon by 50. def attack(self, other): print(self.get_name() + “!”) other.decrease_hp(50)

32 A N OTE A BOUT D OUBLE U NDERSCORES All instance variables so far were preceded by double underscores. This is not necessary! The double underscores tell Python, and other Python programmers, that this variable is not to be used directly outside the class. It is necessary for __init__ though (which is not an instance variable)! We will see why tomorrow.

33 A N OTE A BOUT D OUBLE U NDERSCORES Python will modify the name of the variable so that you cannot use it directly outside the class. You can find out the new name (using dir ), but if you need this extra effort, you are either debugging your code or doing something wrong.

34 A N OTE A BOUT D OUBLE U NDERSCORES The code from before could have been class Pokemon: total_pokemon = 0 def __init__(self, name, owner, hit_pts): self.name = name self.owner = owner self.hp = hit_pts Pokemon.total_pokemon += 1

35 A N OTE A BOUT D OUBLE U NDERSCORES We can then obtain the attributes more directly. >>> ashs_pikachu = Pokemon(‘Pikachu’, ‘Ash’, 300) >>> mistys_togepi = Pokemon(‘Togepi’, ‘Misty’, 245) >>> mistys_togepi.owner ‘Misty’ >>> ashs_pikachu.hp 300 >>> ashs_pikachu.increase_hp(150) >>> ashs_pikachu.hp 450

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

37 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).

38 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!

39 B REAK

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

41 I NHERITANCE We would like to have different kinds of Pokémon, 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?

42 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)

43 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 of the WaterPokemon class. The WaterPokemon class is the subclass of the Pokemon class.

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

45 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

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

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

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

49 I NHERITANCE : W HAT H APPENS H ERE ? class ElectricPokemon(Pokemon): def __init__(self, name, owner, hp, origin): self.__origin = origin ashs_pikachu = ElectricPokemon(‘Pikachu’, ‘Ash’, 300, ‘Pallet Town’) ashs_pikachu.get_hit_pts()

50 I NHERITANCE : W HAT H APPENS H ERE ? One fix is to first call the constructor of the superclass. The constructor of the subclass overrode the constructor of the superclass, which is why the other instance variables were never assigned. class ElectricPokemon(Pokemon): def __init__(self, name, owner, hp, origin): Pokemon.__init__(self, name, owner, hp) self.__origin = origin

51 C ONCLUSION Object-oriented programming is another paradigm that makes objects its central players, not functions. Objects are pieces of data and the associated behavior. Classes define an object, and can inherit methods and instance variables from each other. Preview: If it looks like a duck and quacks like a duck, is it a duck?