guide to programming with python n.
Skip this Video
Loading SlideShow in 5 Seconds..
Guide to Programming with Python PowerPoint Presentation
Download Presentation
Guide to Programming with Python

Loading in 2 Seconds...

play fullscreen
1 / 23

Guide to Programming with Python - PowerPoint PPT Presentation

  • Uploaded on

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)

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation

PowerPoint Slideshow about 'Guide to Programming with Python' - giacomo-rollins

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
guide to programming with python

Guide to Programming with Python

Chapter Nine


Working with multiple objects

oop so far
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): = name

self.fuel = fuel

def status(self):


myship = Ship("Appolo")


  • Object encapsulation & respect privacy
this week s objectives
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
Inheritance Models “is a” Relationship


Sports car










Guide to Programming with Python

using inheritance to create new classes
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
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
Inheritance Example: Animal Class

class Animal(object):

def __init__(self, name): # Constructor = name

def get_name(self):


class Cat(Animal):

def talk(self):

return 'Meow!'

class Dog(Animal):

def talk(self):

return 'Woof! Woof!'

animals = [Cat('Missy'), Cat('Mr. Bojangles'),


for animal in animals:

print + ' 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
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
Overriding to Create a New Version

class Animal(object):

def __init__(self, name): = name

def talk(self):

return 'Hello!'

class Cat(Animal):

def talk(self):

return 'Meow!'

animal a animal b
Animal A > Animal B?

class Animal(object):

def __init__(self, name, age): = name

self.age = age

def get_name(self):


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
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
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
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 Catobject, you get different result than when you invoke thesamemethod of a Animal (or Dog) object

Guide to Programming with Python

summary what can be done through inheritance
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
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
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
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
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()


# here an object is passed to a function of another object

Guide to Programming with Python

combining objects
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
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 Cardobject with rank "A" and suit "d" is the ace of diamonds

print card1

blackjack game the hand class
Blackjack Game: the Hand Class

class Hand(object):

""" A hand of playing cards. """

def __init__(self): = [] #attribute – a list of Card objects

def __str__(self): #special function, returns string for entire hand


reply = ""

for card in

reply += str(card) + " "


reply = "<empty>"

return reply

def add(self, card): #adds card to list of cards

def give(self, card, other_hand):


combining objects1
Combining Objects

my_hand = Hand()

card1 = Card("A", "c")

card1 = Card("2", "c")



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

  • 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