1 / 23

Guide to Programming with Python

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)

Télécharger la présentation

Guide to Programming with Python

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

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

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

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

  7. 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): def talk(self): 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

More Related