Guide to Programming with Python

Slides:



Advertisements
Similar presentations
Object-Oriented Programming
Advertisements

Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Chapter 1 Inheritance University Of Ha’il.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
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:
OOP - Object Oriented Programming Object Oriented Programming is an approach to programming that was developed to make large programs easier to manage.
CS 211 Inheritance AAA.
Inheritance Definition Relationships Member Access Control Data Encapsulation Overloading vs. Overriding Constructors & Destructors.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
BACS 287 Basics of Object-Oriented Programming 1.
Guide to Programming with Python
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
I210 review (for final exam) Fall 2011, IUB. What’s in the Final Exam Multiple Choice (5) Short Answer (5) Program Completion (3) Note: A single-sided.
LECTURE 07 Programming using C# Inheritance
Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game.
Inheritance using Java
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
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.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Week Inheritance and Polymorphism. Introduction Classes allow you to modify a program without really making changes to it. To elaborate, by subclassing.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
1. 2 Object-Oriented Concept Class & Object Object-Oriented Characteristics How does it work? Relationships Between Classes Development Tools Advantage.
11 Chapter 11 Object-Oriented Databases Database Systems: Design, Implementation, and Management 4th Edition Peter Rob & Carlos Coronel.
Guide to Programming with Python
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
Chapter 12 Support for Object oriented Programming.
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
Peyman Dodangeh Sharif University of Technology Fall 2014.
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
Review Class Inheritance, Abstract, Interfaces, Polymorphism, GUI (MVC)
November 28, 2005ICP: Chapter 9: Object Oriented Programming 1 Introduction to Computer Programming Chapter 9: Object Oriented Programming Michael Scherger.
Object Oriented Programming
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Coming up: Inheritance
Creating Classes from Other Classes Appendix D © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Object Oriented Programming In Python
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
BY:- TOPS Technologies
Object-Oriented Programming (OOP) in Python References: Chapter 8.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
CMSC201 Computer Science I for Majors Lecture 18 – Classes and Modules (Continued, Part 3) Prof. Katherine Gibson Based on slides from the.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Object-Oriented Programming
OOP - Object Oriented Programming
Object-Oriented Programming Concepts
JAVA By Waqas.
Lecture 12 Inheritance.
Object-Oriented Programming (OOP) in Python
Object Oriented Programming in Java
An Introduction to Inheritance
Lecture VI Objects The OOP Concept Defining Classes Methods
Chapter 10 Thinking in Objects
Object-oriented programming
Inheritance Basics Programming with Inheritance
Guide to Programming with Python
Week 6 Object-Oriented Programming (2): Polymorphism
Advanced Programming Behnam Hatami Fall 2017.
Computer Programming with JAVA
Guide to Programming with Python Book is by Michael Dawson
Workshop for Programming And Systems Management Teachers
Object Oriented Programming in A Level
Prof. Katherine Gibson Prof. Jeremy Dixon
Presentation transcript:

Guide to Programming with Python Chapter Nine Inheritance Working with multiple objects

OOP So Far Object-oriented programming is a programming language model organized around "objects” An object is a software bundle of related attributes and behavior (methods) A class is a blueprint or prototype from which objects are created class Player(object): def __init__(self, name = "Enterprise", fuel = 0): self.name = name self.fuel = fuel def status(self): ... myship = Ship("Appolo") myship.status() Object encapsulation & respect privacy

This Week’s Objectives Inheritance makes objects (classes) special Derive new classes from existing ones Extend the definition of existing classes Override method definitions of existing classes Create objects of different classes in the same program Allow objects to communicate with each other Create more complex objects by combining simpler ones The Blackjack Game Guide to Programming with Python

Inheritance Models “is a” Relationship Car Van Sports car Convertible Animals Reptile Mammals Fish Dog Cat Human Guide to Programming with Python

Using Inheritance to Create New Classes Inheritance: An element of OOP that allows a new class to be based on an existing one where the new automatically gets (or inherits) all of the methods and attributes of the existing class The children classes get all the capabilities (methods) and properties (attributes) the parent class has; the children classes are also called derived classes Get the code for free! (code-reuse) – inheritance allows a new class to re-use code which already existed in another class (the parent class) Guide to Programming with Python

Derived Classes are New Classes To create specializations of existing classes or objects by adding new attributes and methods! often called subtyping when applied to classes. In specialization, the new class or object has data or behavior aspects that are not part of the inherited class. Over-ridding (e.g., over-ridding of the + operator, so + has different meaning, addition of two numbers, concatenation of two strings, etc) – the same method that does something different Guide to Programming with Python

Inheritance Example: Animal Class class Animal(object): def __init__(self, name): # Constructor self.name = name def get_name(self): return self.name class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Mr. Bojangles'), Dog('Lassie')] for animal in animals: print animal.talk() + ' I am ' + animal.get_name() Base class: A class upon which another is based; it is inherited from by a derived class Derived class: A class that is based upon another class; it inherits from a base class

Altering the Behavior of Inherited Methods: Overriding Override: To redefine how inherited method of base class works in derived class Two choices when overriding Completely new functionality vs. overridden method Incorporate functionality of overridden method, add more Guide to Programming with Python

Overriding to Create a New Version class Animal(object): def __init__(self, name): self.name = name def talk(self): return 'Hello!' class Cat(Animal): return 'Meow!'

Animal A > Animal B? class Animal(object): def __init__(self, name, age): self.name = name self.age = age def get_name(self): return self.name def __gt__(self, other): #override comparison operators return self.age > other.age print Animal('Missy', 4) > Animal('Lassie', 3) Guide to Programming with Python

Overriding to Add More One can incorporate inherited method’s functionality in overridden method Class Card(object): ... class Positionable_Card(Card): def __init__(self, rank, suit, face_up = True): super(Positionable_Card, self).__init__(rank, suit) #invoke parent’s method by calling super() self.is_face_up = face_up Superclass: Another name for a base class Card is the superclass of Positionable_Card

Invoking Base Class Methods Incorporate inherited method’s functionality by calling super() Positionable_Card constructor invokes Card constructor and creates new attribute super() lets you invoke the method of a superclass First argument is the class name, Positionable_Card Second is reference to object itself, self Last is superclass method to call with parameters sent, __init__(rank, suit) Guide to Programming with Python

Understanding Polymorphism Polymorphism: Aspect of object-oriented programming that allows you to send same message to objects of different classes, related by inheritance, and achieve different but appropriate results for each object When you invoke talk() method of Cat object, you get different result than when you invoke the same method of a Animal (or Dog) object Guide to Programming with Python

Summary: What can be Done Through Inheritance New class gets all methods and attributes of existing class New class can also define additional methods and attributes, to create more specialized version of existing class New class can override the old methods When overriding a method, the new definition can have completely different functionality than the original definition or the new definition can incorporate the functionality of the original The super() function allows you to invoke the method of a superclass

A Little More on Inheritance Need to avoid yo-yo problem (caused by the too complicated inheritance hierarchy) Python supports a limited form of multiple inheritance (applies depth-first, left-to-right rule) class DerivedClass(Base1, Base2, Base3): ... Python interprets this by applying the depth-first, left-to right rule: if an attribute is not found in DerivedClass, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on)

Working with Multiple Objects We can have multiple objects in a program Message: Communication between objects; one object sends another a message when it invokes a method of the other (We already know that we can exchange information among functions through parameters and return values) Guide to Programming with Python

The Alien Blaster Program Figure 9.3: Visual representation of objects exchanging a message hero, a Player object, sends invader, an Alien object, a message. Guide to Programming with Python

Communications between Objects (Alien and Player) class Player(object): def blast(self, enemy): #enemy refers to the Alien object print "The player blasts an enemy." enemy.die() #invokes the Alien object’s die()method class Alien(object): def die(self): print "Good-bye, cruel universe.” hero = Player() invader = Alien() hero.blast(invader) # here an object is passed to a function of another object Guide to Programming with Python

Combining Objects Real-world objects often made up of other objects Can mimic composition and collection in OOP Drag racer composed of body, tires, and engine Drag_Racer class with attribute engine that references Race_Engine object Zoo is collection of animals Zoo class that has an attribute animals which is a list of different Animal objects Guide to Programming with Python

Blackjack Game: the Card Class class Card(object): """ A playing card. """ RANKS = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] SUITS = ["c", "d", "h", "s"] #class attributes def __init__(self, rank, suit): self.rank = rank #object attributes self.suit = suit def __str__(self): reply = self.rank + self.suit return reply card1 = Card(”A", ”d") # A Card object with rank "A" and suit "d" is the ace of diamonds print card1

Blackjack Game: the Hand Class class Hand(object): """ A hand of playing cards. """ def __init__(self): self.cards = [] #attribute – a list of Card objects def __str__(self): #special function, returns string for entire hand if self.cards: reply = "" for card in self.cards: reply += str(card) + " " else: reply = "<empty>" return reply def add(self, card): #adds card to list of cards self.cards.append(card) def give(self, card, other_hand): self.cards.remove(card) other_hand.add(card)

Combining Objects my_hand = Hand() card1 = Card("A", "c") card1 = Card("2", "c") my_hand.add(card1) my_hand.add(card2) print my_hand # Ac 2c your_hand = Hand() my_hand.give(card1, your_hand) my_hand.give(card2, your_hand) print your_hand # Ac 2c Guide to Programming with Python

Summary In object-oriented programming, objects can send messages to each other by invoking each other’s methods Objects can be composed of other objects or have collections of objects Guide to Programming with Python