Movatterモバイル変換


[0]ホーム

URL:


Uploaded byajajkhan16
PPT, PDF35 views

Programming in python and introduction.ppt

This document is a guide on object-oriented programming in Python, covering topics such as class creation, object interaction, inheritance, and method overriding. It uses examples like a Blackjack game and card classes to illustrate concepts such as object composition, polymorphism, and module creation. The document emphasizes how objects can communicate through methods, enabling the development of complex applications.

Embed presentation

Download to read offline
Guide to Programming withPythonChapter NineObject-Oriented Programming: The BlackjackGame
Guide to Programming with Python 2Objectives• Create objects of different classes in the sameprogram• Allow objects to communicate with each other• Create more complex objects by combining simplerones• Derive new classes from existing ones• Extend the definition of existing classes• Override method definitions of existing classes
Guide to Programming with Python 3The Blackjack GameFigure 9.1: Sample run of the Blackjack gameOne player wins, the other is not so lucky.
Guide to Programming with Python 4Sending and Receiving Messages• Object-oriented program like an ecosystem• Objects like organisms• Organisms interact and so do objects• Message: Communication between objects; oneobject sends another a message when it invokes amethod of the other
Guide to Programming with Python 5The Alien Blaster ProgramFigure 9.2: Sample run of the Alien Blaster programBattle description is result of objects exchanging message.
Guide to Programming with Python 6The Alien Blaster Program (continued)Figure 9.3: Visual representation of objects exchanging a messagehero, a Player object, sends invader, an Alien object, a message.
Guide to Programming with Python 7The Alien Blaster Program (continued)class Player(object):def blast(self, enemy):print "The player blasts an enemy."enemy.die()class Alien(object):def die(self):print "Good-bye, cruel universe."hero = Player()invader = Alien()hero.blast(invader)
Guide to Programming with Python 8Sending a Messageclass Player(object):def blast(self, enemy):print "The player blasts an enemy."enemy.die()...hero.blast(invader)• hero.blast() method is passed invader; i.e.,the Player blast() method is passed an Alien object• In blast(), enemy refers to the Alien object (invader)• blast() invokes the Alien object’s die() method; i.e.,the Player object sends the Alien object a messagetelling it to diealien_blaster.py
Guide to Programming with Python 9Combining Objects• Real-world objects are often made up of otherobjects• Can mimic composition and collection in OOP• Drag racer composed of body, tires, and engine– Drag_Racer class with attribute engine that is aRace_Engine object• Zoo is collection of animals– Zoo class that has an attribute animals which is a listof different Animal objects
Guide to Programming with Python 10The Playing Cards ProgramFigure 9.4: Sample run of the Playing Cards programEach Hand object has a collection of Card objects.
Guide to Programming with Python 11Creating the Card Classclass Card(object):""" A playing card. """RANKS = ["A", "2", "3", "4", "5", "6", "7","8", "9", "10", "J", "Q", "K"]SUITS = ["c", "d", "h", "s"]def __init__(self, rank, suit):self.rank = rankself.suit = suitdef __str__(self):reply = self.rank + self.suitreturn reply
Guide to Programming with Python 12Creating the Card Class (continued)• Card object rank attribute represents rank of card– RANKS class attribute has all possible values– "A" ace, "J" jack, "Q" queen, "K" king, "2" - "10"numeric values• Card object suit attribute represents suit of card– SUITS class attribute has all possible values– "c" clubs, "d" diamonds, "h" hearts, "s" spades• A Card object with rank "A" and suit "d" is the aceof diamonds
Guide to Programming with Python 13Creating the Hand Classclass Hand(object):""" A hand of playing cards. """def __init__(self):self.cards = []def __str__(self):if self.cards:reply = ""for card in self.cards:reply += str(card) + " "else:reply = "<empty>"return reply
Guide to Programming with Python 14Creating the Hand Class (continued)def clear(self):self.cards = []def add(self, card):self.cards.append(card)def give(self, card, other_hand):self.cards.remove(card)other_hand.add(card)
Guide to Programming with Python 15Creating the Hand Class (continued)• Attribute– cards is list of Card objects• Methods– __str__() returns string for entire hand– clear() clears list of cards– add() adds card to list of cards– give() removes card from current hand and adds toanother hand
Guide to Programming with Python 16Using Card Objectscard1 = Card(rank = "A", suit = "c")card2 = Card(rank = "2", suit = "c")card3 = Card(rank = "3", suit = "c")card4 = Card(rank = "4", suit = "c")card5 = Card(rank = "5", suit = "c")print card1 # Acprint card2 # 2cprint card3 # 3cprint card4 # 4cprint card5 # 5c
Guide to Programming with Python 17Combining Card Objects Using a HandObjectmy_hand = Hand()print my_hand # <empty>my_hand.add(card1)my_hand.add(card2)my_hand.add(card3)my_hand.add(card4)my_hand.add(card5)print my_hand # Ac 2c 3c 4c 5c
Guide to Programming with Python 18Combining Card Objects Using a HandObject (continued)your_hand = Hand()my_hand.give(card1, your_hand)my_hand.give(card2, your_hand)print your_hand # Ac 2cprint my_hand # 3c 4c 5cmy_hand.clear()print my_hand # <empty>playing_cards.py
Guide to Programming with Python 19Using Inheritance to Create NewClasses• Inheritance: An element of OOP that allows a newclass to be based on an existing one where thenew automatically gets (or inherits) all of themethods and attributes of the existing class• Like getting all the work that went into the existingclass for free
Guide to Programming with Python 20Extending a Class ThroughInheritance• Inheritance is used to create a more specializedversion of an existing class• The new class gets all the methods and attributes ofthe existing class• The new class can also define additional methods andattributes• Drag_Racer class with methods stop() and go()• Clean_Drag_Racer based on Drag_Racer()– Automatically inherits stop() and go()– Can define new method, clean(), for cleaningwindshield
Guide to Programming with Python 21The Playing Cards 2.0 ProgramFigure 9.5: Sample run of the Playing Cards 2.0 programThe Deck object inherits all of the methods of the Hand class.
Guide to Programming with Python 22Creating a Base Class(Same as before)class Hand(object):""" A hand of playing cards. """def __init__(self):self.cards = []def __str__(self):if self.cards:reply = ""for card in self.cards:reply += str(card) + " "else:reply = "<empty>"return rep
Guide to Programming with Python 23Creating a Base Class (continued)(Same as before)def clear(self):self.cards = []def add(self, card):self.cards.append(card)def give(self, card, other_hand):self.cards.remove(card)other_hand.add(card)
Guide to Programming with Python 24Inheriting from a Base Classclass Deck(Hand):• 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 anotherclass; it inherits from a base class• Hand is base class• Deck is derived class
Guide to Programming with Python 25Inheriting from a Base Class(continued)• Deck inherits Hand attribute:cards• Deck inherits all Hand methods:__init__()__str__()clear()add()give()
Guide to Programming with Python 26Extending a Derived Classclass Deck(Hand):""" A deck of playing cards. """def populate(self):for suit in Card.SUITS:for rank in Card.RANKS:self.add(Card(rank, suit))def shuffle(self):import randomrandom.shuffle(self.cards)
Guide to Programming with Python 27Extending a Derived Class (continued)def deal(self, hands, per_hand = 1):for rounds in range(per_hand):for hand in hands:if self.cards: # if len(self.cards) > 0top_card = self.cards[0]self.give(top_card, hand)else:print "Out of cards!"
Guide to Programming with Python 28Extending a Derived Class (continued)• In addition to methods Deck inherits, it defines newmethods:populate()shuffle()deal()
Guide to Programming with Python 29Using the Derived Classdeck1 = Deck()print deck1 # <empty>deck1.populate()print deck1 # ordered deckdeck1.shuffle()print deck1 # shuffled deck
Guide to Programming with Python 30Using the Derived Class (continued)my_hand = Hand()your_hand = Hand()hands = [my_hand, your_hand]deck1.deal(hands, per_hand = 5)print my_hand # 5 alternating cards from deckprint your_hand # 5 alternating cards from deckprint deck1 # deck minus first 10 cardsdeck1.clear()print deck1 # <empty>playing_cards2.py
Guide to Programming with Python 31Altering the Behavior of InheritedMethods• Override: To redefine how inherited method ofbase class works in derived class• Two choices when overriding– Completely new functionality vs. overridden method– Incorporate functionality of overridden method, addmore
Altering the Behavior of InheritedMethods (continued)• Drag_Racer with stop() method that applies brakes• Parachute_Racer based on Drag_Racer overridesstop() method, two choices– Overridden stop() method shifts into reverse– Overridden stop() method applies brakes (usingthe overridden method) and releases parachuteGuide to Programming with Python 32
Guide to Programming with Python 33The Playing Cards 3.0 ProgramFigure 9.6: Sample run of the Playing Cards programBy overriding __str__(), objects of derived classes print differently.
Guide to Programming with Python 34Creating a Base Class(Same as before)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"]def __init__(self, rank, suit):self.rank = rankself.suit = suitdef __str__(self):reply = self.rank + self.suitreturn reply
Guide to Programming with Python 35Overriding Base Class Methodsclass Unprintable_Card(Card):....def __str__(self):return "<unprintable>"• Unprintable_Card– Inherits all methods of Card– Overrides inherited method __str__()– Printed object displayed as <unprintable>• A derived class has no effect on a base class
Guide to Programming with Python 36Invoking Base Class Methods• In overridden method, can incorporate inherited method’sfunctionality• Suppose we want to have a card that can be face up or facedown…class Positionable_Card(Card):def __init__(self, rank, suit, face_up = True):super(Positionable_Card, self).__init__(rank, suit)self.is_face_up = face_up• Superclass: Another name for a base class• Card is the superclass of Positionable_Card
Guide to Programming with Python 37Invoking Base Class Methods(continued)• Incorporate inherited method’s functionality bycalling super()• Positionable_Card constructor invokes Cardconstructor and creates new attribute• super() lets you invoke the method of a superclass– First argument is the base class, Positionable_Card– Second is a reference to the object itself, self– Last is the superclass method you want to call withits parameters, __init__(rank, suit)
Guide to Programming with Python 38Invoking Base Class Methods(continued)class Positionable_Card(Card):def __str__(self):if self.is_face_up:reply = super(Positionable_Card, self).__str__()else:reply = "XX"return repdef flip(self):self.is_face_up = not self.is_face_up• __str__() invokes superclass __str__() method ifcard is face up; otherwise, returns "XX"
Guide to Programming with Python 39Using the Derived Classescard1 = Card("A", "c")card2 = Unprintable_Card("A", "d")card3 = Positionable_Card("A", "h")print card1 # Acprint card2 # <unprintable>print card3 # Ahcard3.flip()print card3 # XXplaying_cards3.py
Guide to Programming with Python 40Understanding Polymorphism• Polymorphism: Aspect of object-orientedprogramming that allows you to send samemessage to objects of different classes, related byinheritance, and achieve different but appropriateresults for each object• When you invoke __str__() method ofUnprintable_Card object, you get different resultthan when you invoke the __str__() method of aCard object
Guide to Programming with Python 41Creating Modules• Create, use, and even share your own modules• Reuse code– Could reuse the Card, Hand, and Deck classes fordifferent card games• Manage large projects– Professional projects can be hundreds of thousandsof lines long– Would be nearly impossible to maintain in one file
Guide to Programming with Python 42The Simple Game ProgramFigure 9.7: Sample run of the Simple Game programProgram uses functions and class from programmer-created module.
Guide to Programming with Python 43Writing Modules• Write module as a collection of relatedprogramming components, like functions andclasses, in single file• File is just Python file with extension .py• Module imported using filename, just like built-inmodules
Guide to Programming with Python 44Writing Modules (continued)games module is file games.pyclass Player(object):""" A player for a game. """def __init__(self, name, score = 0):self.name = nameself.score = scoredef __str__(self):reply = self.name + ":t" + str(self.score)return reply
Guide to Programming with Python 45Writing Modules (continued)def ask_yes_no(question):"""Ask a yes or no question."""response = Nonewhile response not in ("y", "n"):response = raw_input(question).lower()return responsedef ask_number(question, low, high):"""Ask for a number within a range."""response = Nonewhile response not in range(low, high):response = int(raw_input(question))return response
Guide to Programming with Python 46Writing Modules (continued)if __name__ == "__main__":print "You ran module but must 'import' it."raw_input("nnPress the enter key to exit.")• __name__ == "__main__" is true if file is run directly;is false if the file is imported as module• If games.py run directly, message displayed that thefile is meant to be importedgames.py
Guide to Programming with Python 47Importing Modulesimport games, random• Import programmer-created module the same wayyou import a built-in module
Guide to Programming with Python 48Using Imported Functions and Classesnum = games.ask_number(question = "How many?",low = 2, high = 5)...player = games.Player(name, score)...again = games.ask_yes_no("Play again? (y/n): ")• Use imported programmer-created modules thesame way as you use imported built-in modulessimple_game.py
Guide to Programming with Python 49The Blackjack Game - ClassesTable 9.1: Blackjack classes
Guide to Programming with Python 50The Blackjack Game – ClassHierarchyFigure 9.8: Blackjack classesInheritance hierarchy of classes for the Blackjack game
Guide to Programming with Python 51The Blackjack Game - PseudocodeDeal each player and dealer initial two cardsFor each playerWhile the player asks for a hit and the player is not bustedDeal the player an additional cardIf there are no players still playingShow the dealer’s two cardsOtherwiseWhile the dealer must hit and the dealer is not bustedDeal the dealer an additional cardIf the dealer is bustedFor each player who is still playingThe player wins
Guide to Programming with Python 52The Blackjack Game – Pseudocode(continued)OtherwiseFor each player who is still playingIf the player’s total is greater than the dealer’s totalThe player winsOtherwise, if the player’s total is less than the dealer’s totalThe player losesOtherwiseThe player pushesblackjack.py
Guide to Programming with Python 53Summary• In object-oriented programming, objects can sendmessages to each other by invoking each other’smethods• Objects can be composed of other objects or havecollections of objects• Inheritance is an aspect of object-orientedprogramming that allows a new class to be basedon an existing one where the new classautomatically gets (or inherits) all of the methodsand attributes of the existing one
Summary (continued)• Inheritance can be used to create a morespecialized version of an existing class• A base class is a class upon which another isbased; it is inherited from by this other class (thederived class)• A derived class is a class that is based uponanother class; it inherits from this other class (abase class)• Superclass is another name for base classGuide to Programming with Python 54
Guide to Programming with Python 55Summary (continued)• A derived class can define new methods andattributes in addition to the ones that it inherits• To override an inherited method is to redefine howthe method of a base class works in a derivedclass• When overriding a method, the new definition canhave completely different functionality than theoriginal definition or the new definition canincorporate the functionality of the original
Guide to Programming with Python 56Summary (continued)• The super() function allows you to invoke themethod of a superclass• Polymorphism is an aspect of object-orientedprogramming that allows you to send the samemessage to objects of different classes, related byinheritance, and achieve different but appropriateresults for each object• You can write, import, and even share your ownmodules
Summary (continued)• You write a module as a collection of relatedprogramming components, like functions andclasses, in a single Python file• Programmer-created modules can be imported thesame way that built-in modules are, with an importstatement• You test to see if __name__ is equal to"__main__" to make a module identify itself assuchGuide to Programming with Python 57

Recommended

PPTX
Python programming computer science and engineering
 
PPTX
Problem solving with python programming OOP's Concept
PPTX
Object Oriented Programming.pptx
PPTX
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
PPT
week 11 inheritance week 11 inheritances
PPT
inheritance in python with full detail.ppt
PPTX
OOPS.pptx
PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
PPT
Introduction to Python For Diploma Students
PPTX
software construction and development week 3 Python lists, tuples, dictionari...
PPTX
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
PDF
Object-Oriented Python 1st Edition Irv Kalb
PPTX
Inheritance
PPTX
Advance python
PPTX
OOPS 46 slide Python concepts .pptx
PDF
Object oriented Programming via python.pdf
PDF
Python unit 3 m.sc cs
PPTX
Object Oriented Programming - Copy.pptxb
PPTX
Class and Objects in python programming.pptx
PPTX
Object oriented programming with python
PPTX
Python OOPs
PDF
Download full ebook of Learning Python 2nd ed Edition Mark Lutz instant downl...
PPTX
arthimetic operator,classes,objects,instant
PPTX
Software Programming with Python II.pptx
PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
PDF
Intro to Python
PPTX
Lec-21-Classes and Object Orientation.pptx
PPTX
6. PRESENTATION REAL TIME OBJECT DETECTION.pptx
PPTX
RQP reverse query processing it's application 2011.pptx

More Related Content

PPTX
Python programming computer science and engineering
 
PPTX
Problem solving with python programming OOP's Concept
PPTX
Object Oriented Programming.pptx
PPTX
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
PPT
week 11 inheritance week 11 inheritances
PPT
inheritance in python with full detail.ppt
PPTX
OOPS.pptx
Python programming computer science and engineering
 
Problem solving with python programming OOP's Concept
Object Oriented Programming.pptx
PYTHON OBJECT-ORIENTED PROGRAMMING.pptx
Unit 3-Classes ,Objects and Inheritance.pdf
week 11 inheritance week 11 inheritances
inheritance in python with full detail.ppt
OOPS.pptx

Similar to Programming in python and introduction.ppt

PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
PPT
Introduction to Python For Diploma Students
PPTX
software construction and development week 3 Python lists, tuples, dictionari...
PPTX
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
PDF
Object-Oriented Python 1st Edition Irv Kalb
PPTX
Inheritance
PPTX
Advance python
PPTX
OOPS 46 slide Python concepts .pptx
PDF
Object oriented Programming via python.pdf
PDF
Python unit 3 m.sc cs
PPTX
Object Oriented Programming - Copy.pptxb
PPTX
Class and Objects in python programming.pptx
PPTX
Object oriented programming with python
PPTX
Python OOPs
PDF
Download full ebook of Learning Python 2nd ed Edition Mark Lutz instant downl...
PPTX
arthimetic operator,classes,objects,instant
PPTX
Software Programming with Python II.pptx
PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
PDF
Intro to Python
PPTX
Lec-21-Classes and Object Orientation.pptx
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Introduction to Python For Diploma Students
software construction and development week 3 Python lists, tuples, dictionari...
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
Object-Oriented Python 1st Edition Irv Kalb
Inheritance
Advance python
OOPS 46 slide Python concepts .pptx
Object oriented Programming via python.pdf
Python unit 3 m.sc cs
Object Oriented Programming - Copy.pptxb
Class and Objects in python programming.pptx
Object oriented programming with python
Python OOPs
Download full ebook of Learning Python 2nd ed Edition Mark Lutz instant downl...
arthimetic operator,classes,objects,instant
Software Programming with Python II.pptx
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Intro to Python
Lec-21-Classes and Object Orientation.pptx

More from ajajkhan16

PPTX
6. PRESENTATION REAL TIME OBJECT DETECTION.pptx
PPTX
RQP reverse query processing it's application 2011.pptx
PPTX
STACK 20 INTERVIEW QUESTIONS and answers for interview.pptx
PPTX
data ebncryption standard with example.pptx
PPTX
SYMMETRIC CYPHER MODELS WITH SUITABLE DIAGRAM.pptx
PPTX
NoSQL 5 2_graph Database Edited - Updated.pptx.pptx
PPTX
loundry app and its advantages Final ppt.pptx
PPTX
search engine and crawler index ranking .pptx
PPT
Unit-4 Cybercrimes-II Mobile and Wireless Devices.ppt
PPTX
CRAWLER,INDEX,RANKING AND ITS WORKING.pptx
PPTX
block cipher and its principle and charateristics.pptx
PDF
searchengineAND ALL ppt-171025105119.pdf
PPTX
LECT-5 Managing Different Data Types, Columnar, Key-Value Stores, Triple and ...
PPTX
first ppt online shopping website and all.pptx
PPTX
Presentation - Smart Vigilance System.pptx
PPTX
mini project Presentation and details of the online plateforms.pptx
PPTX
Benchmarking and Design of Hybrid Transformer-Quantum Classifiers for.pptx
PDF
hill cipher with example and solving .pdf
PDF
STORMPresentation and all about storm_FINAL.pdf
PDF
39.-Introduction-to-Sparkspark and all-1.pdf
6. PRESENTATION REAL TIME OBJECT DETECTION.pptx
RQP reverse query processing it's application 2011.pptx
STACK 20 INTERVIEW QUESTIONS and answers for interview.pptx
data ebncryption standard with example.pptx
SYMMETRIC CYPHER MODELS WITH SUITABLE DIAGRAM.pptx
NoSQL 5 2_graph Database Edited - Updated.pptx.pptx
loundry app and its advantages Final ppt.pptx
search engine and crawler index ranking .pptx
Unit-4 Cybercrimes-II Mobile and Wireless Devices.ppt
CRAWLER,INDEX,RANKING AND ITS WORKING.pptx
block cipher and its principle and charateristics.pptx
searchengineAND ALL ppt-171025105119.pdf
LECT-5 Managing Different Data Types, Columnar, Key-Value Stores, Triple and ...
first ppt online shopping website and all.pptx
Presentation - Smart Vigilance System.pptx
mini project Presentation and details of the online plateforms.pptx
Benchmarking and Design of Hybrid Transformer-Quantum Classifiers for.pptx
hill cipher with example and solving .pdf
STORMPresentation and all about storm_FINAL.pdf
39.-Introduction-to-Sparkspark and all-1.pdf

Recently uploaded

PPTX
clustering type :hierarchical clustering.pptx
PDF
222109_MD_MILTON_HOSSAIN_26TH_BATCH_REGULAR_PMIT V5.pdf
PDF
k-means algorithm with numerical solution.pdf
PDF
Event #3_ Build a Gemini Bot, Together with GitHub_private.pdf
PDF
application of matrix in computer science
PPTX
Generative AI Deep Dive: Architectures, Mechanics, and Future Applications
PDF
Why Buildings Crumble Before Their Time And How We Can Build a Legacy
PPTX
ensemble learning of machine learning .pptx
PDF
Advancements in Telecommunication for Disaster Management (www.kiu.ac.ug)
PDF
@Regenerative braking system of DC motor
PDF
November_2025 Top 10 Read Articles in Computer Networks & Communications.pdf
PDF
Small Space Big Design - Amar DeXign Scape
PDF
Soil Permeability and Seepage-Irrigation Structures
PPTX
Blockchain and cryptography Lecture Notes
PPTX
31.03.24 - 7.CURRICULUM & TEACHING - LEARNING PROCESS IMPLEMENTATION DETAILS....
PPTX
Presentation 1.pptx WHAT IS ARTIFICIAL INTELLIGENCE?
PPTX
waste to energy deck v.3.pptx changing garbage to electricity
PPTX
Waste to Energy - G2 Ethanol.pptx to process
PPTX
TRANSPORTATION ENGINEERING Unit-5.1.pptx
PPT
399-Cathodic-Protection-Presentation.ppt
 
clustering type :hierarchical clustering.pptx
222109_MD_MILTON_HOSSAIN_26TH_BATCH_REGULAR_PMIT V5.pdf
k-means algorithm with numerical solution.pdf
Event #3_ Build a Gemini Bot, Together with GitHub_private.pdf
application of matrix in computer science
Generative AI Deep Dive: Architectures, Mechanics, and Future Applications
Why Buildings Crumble Before Their Time And How We Can Build a Legacy
ensemble learning of machine learning .pptx
Advancements in Telecommunication for Disaster Management (www.kiu.ac.ug)
@Regenerative braking system of DC motor
November_2025 Top 10 Read Articles in Computer Networks & Communications.pdf
Small Space Big Design - Amar DeXign Scape
Soil Permeability and Seepage-Irrigation Structures
Blockchain and cryptography Lecture Notes
31.03.24 - 7.CURRICULUM & TEACHING - LEARNING PROCESS IMPLEMENTATION DETAILS....
Presentation 1.pptx WHAT IS ARTIFICIAL INTELLIGENCE?
waste to energy deck v.3.pptx changing garbage to electricity
Waste to Energy - G2 Ethanol.pptx to process
TRANSPORTATION ENGINEERING Unit-5.1.pptx
399-Cathodic-Protection-Presentation.ppt
 

Programming in python and introduction.ppt

  • 1.
    Guide to ProgrammingwithPythonChapter NineObject-Oriented Programming: The BlackjackGame
  • 2.
    Guide to Programmingwith Python 2Objectives• Create objects of different classes in the sameprogram• Allow objects to communicate with each other• Create more complex objects by combining simplerones• Derive new classes from existing ones• Extend the definition of existing classes• Override method definitions of existing classes
  • 3.
    Guide to Programmingwith Python 3The Blackjack GameFigure 9.1: Sample run of the Blackjack gameOne player wins, the other is not so lucky.
  • 4.
    Guide to Programmingwith Python 4Sending and Receiving Messages• Object-oriented program like an ecosystem• Objects like organisms• Organisms interact and so do objects• Message: Communication between objects; oneobject sends another a message when it invokes amethod of the other
  • 5.
    Guide to Programmingwith Python 5The Alien Blaster ProgramFigure 9.2: Sample run of the Alien Blaster programBattle description is result of objects exchanging message.
  • 6.
    Guide to Programmingwith Python 6The Alien Blaster Program (continued)Figure 9.3: Visual representation of objects exchanging a messagehero, a Player object, sends invader, an Alien object, a message.
  • 7.
    Guide to Programmingwith Python 7The Alien Blaster Program (continued)class Player(object):def blast(self, enemy):print "The player blasts an enemy."enemy.die()class Alien(object):def die(self):print "Good-bye, cruel universe."hero = Player()invader = Alien()hero.blast(invader)
  • 8.
    Guide to Programmingwith Python 8Sending a Messageclass Player(object):def blast(self, enemy):print "The player blasts an enemy."enemy.die()...hero.blast(invader)• hero.blast() method is passed invader; i.e.,the Player blast() method is passed an Alien object• In blast(), enemy refers to the Alien object (invader)• blast() invokes the Alien object’s die() method; i.e.,the Player object sends the Alien object a messagetelling it to diealien_blaster.py
  • 9.
    Guide to Programmingwith Python 9Combining Objects• Real-world objects are often made up of otherobjects• Can mimic composition and collection in OOP• Drag racer composed of body, tires, and engine– Drag_Racer class with attribute engine that is aRace_Engine object• Zoo is collection of animals– Zoo class that has an attribute animals which is a listof different Animal objects
  • 10.
    Guide to Programmingwith Python 10The Playing Cards ProgramFigure 9.4: Sample run of the Playing Cards programEach Hand object has a collection of Card objects.
  • 11.
    Guide to Programmingwith Python 11Creating the Card Classclass Card(object):""" A playing card. """RANKS = ["A", "2", "3", "4", "5", "6", "7","8", "9", "10", "J", "Q", "K"]SUITS = ["c", "d", "h", "s"]def __init__(self, rank, suit):self.rank = rankself.suit = suitdef __str__(self):reply = self.rank + self.suitreturn reply
  • 12.
    Guide to Programmingwith Python 12Creating the Card Class (continued)• Card object rank attribute represents rank of card– RANKS class attribute has all possible values– "A" ace, "J" jack, "Q" queen, "K" king, "2" - "10"numeric values• Card object suit attribute represents suit of card– SUITS class attribute has all possible values– "c" clubs, "d" diamonds, "h" hearts, "s" spades• A Card object with rank "A" and suit "d" is the aceof diamonds
  • 13.
    Guide to Programmingwith Python 13Creating the Hand Classclass Hand(object):""" A hand of playing cards. """def __init__(self):self.cards = []def __str__(self):if self.cards:reply = ""for card in self.cards:reply += str(card) + " "else:reply = "<empty>"return reply
  • 14.
    Guide to Programmingwith Python 14Creating the Hand Class (continued)def clear(self):self.cards = []def add(self, card):self.cards.append(card)def give(self, card, other_hand):self.cards.remove(card)other_hand.add(card)
  • 15.
    Guide to Programmingwith Python 15Creating the Hand Class (continued)• Attribute– cards is list of Card objects• Methods– __str__() returns string for entire hand– clear() clears list of cards– add() adds card to list of cards– give() removes card from current hand and adds toanother hand
  • 16.
    Guide to Programmingwith Python 16Using Card Objectscard1 = Card(rank = "A", suit = "c")card2 = Card(rank = "2", suit = "c")card3 = Card(rank = "3", suit = "c")card4 = Card(rank = "4", suit = "c")card5 = Card(rank = "5", suit = "c")print card1 # Acprint card2 # 2cprint card3 # 3cprint card4 # 4cprint card5 # 5c
  • 17.
    Guide to Programmingwith Python 17Combining Card Objects Using a HandObjectmy_hand = Hand()print my_hand # <empty>my_hand.add(card1)my_hand.add(card2)my_hand.add(card3)my_hand.add(card4)my_hand.add(card5)print my_hand # Ac 2c 3c 4c 5c
  • 18.
    Guide to Programmingwith Python 18Combining Card Objects Using a HandObject (continued)your_hand = Hand()my_hand.give(card1, your_hand)my_hand.give(card2, your_hand)print your_hand # Ac 2cprint my_hand # 3c 4c 5cmy_hand.clear()print my_hand # <empty>playing_cards.py
  • 19.
    Guide to Programmingwith Python 19Using Inheritance to Create NewClasses• Inheritance: An element of OOP that allows a newclass to be based on an existing one where thenew automatically gets (or inherits) all of themethods and attributes of the existing class• Like getting all the work that went into the existingclass for free
  • 20.
    Guide to Programmingwith Python 20Extending a Class ThroughInheritance• Inheritance is used to create a more specializedversion of an existing class• The new class gets all the methods and attributes ofthe existing class• The new class can also define additional methods andattributes• Drag_Racer class with methods stop() and go()• Clean_Drag_Racer based on Drag_Racer()– Automatically inherits stop() and go()– Can define new method, clean(), for cleaningwindshield
  • 21.
    Guide to Programmingwith Python 21The Playing Cards 2.0 ProgramFigure 9.5: Sample run of the Playing Cards 2.0 programThe Deck object inherits all of the methods of the Hand class.
  • 22.
    Guide to Programmingwith Python 22Creating a Base Class(Same as before)class Hand(object):""" A hand of playing cards. """def __init__(self):self.cards = []def __str__(self):if self.cards:reply = ""for card in self.cards:reply += str(card) + " "else:reply = "<empty>"return rep
  • 23.
    Guide to Programmingwith Python 23Creating a Base Class (continued)(Same as before)def clear(self):self.cards = []def add(self, card):self.cards.append(card)def give(self, card, other_hand):self.cards.remove(card)other_hand.add(card)
  • 24.
    Guide to Programmingwith Python 24Inheriting from a Base Classclass Deck(Hand):• 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 anotherclass; it inherits from a base class• Hand is base class• Deck is derived class
  • 25.
    Guide to Programmingwith Python 25Inheriting from a Base Class(continued)• Deck inherits Hand attribute:cards• Deck inherits all Hand methods:__init__()__str__()clear()add()give()
  • 26.
    Guide to Programmingwith Python 26Extending a Derived Classclass Deck(Hand):""" A deck of playing cards. """def populate(self):for suit in Card.SUITS:for rank in Card.RANKS:self.add(Card(rank, suit))def shuffle(self):import randomrandom.shuffle(self.cards)
  • 27.
    Guide to Programmingwith Python 27Extending a Derived Class (continued)def deal(self, hands, per_hand = 1):for rounds in range(per_hand):for hand in hands:if self.cards: # if len(self.cards) > 0top_card = self.cards[0]self.give(top_card, hand)else:print "Out of cards!"
  • 28.
    Guide to Programmingwith Python 28Extending a Derived Class (continued)• In addition to methods Deck inherits, it defines newmethods:populate()shuffle()deal()
  • 29.
    Guide to Programmingwith Python 29Using the Derived Classdeck1 = Deck()print deck1 # <empty>deck1.populate()print deck1 # ordered deckdeck1.shuffle()print deck1 # shuffled deck
  • 30.
    Guide to Programmingwith Python 30Using the Derived Class (continued)my_hand = Hand()your_hand = Hand()hands = [my_hand, your_hand]deck1.deal(hands, per_hand = 5)print my_hand # 5 alternating cards from deckprint your_hand # 5 alternating cards from deckprint deck1 # deck minus first 10 cardsdeck1.clear()print deck1 # <empty>playing_cards2.py
  • 31.
    Guide to Programmingwith Python 31Altering the Behavior of InheritedMethods• Override: To redefine how inherited method ofbase class works in derived class• Two choices when overriding– Completely new functionality vs. overridden method– Incorporate functionality of overridden method, addmore
  • 32.
    Altering the Behaviorof InheritedMethods (continued)• Drag_Racer with stop() method that applies brakes• Parachute_Racer based on Drag_Racer overridesstop() method, two choices– Overridden stop() method shifts into reverse– Overridden stop() method applies brakes (usingthe overridden method) and releases parachuteGuide to Programming with Python 32
  • 33.
    Guide to Programmingwith Python 33The Playing Cards 3.0 ProgramFigure 9.6: Sample run of the Playing Cards programBy overriding __str__(), objects of derived classes print differently.
  • 34.
    Guide to Programmingwith Python 34Creating a Base Class(Same as before)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"]def __init__(self, rank, suit):self.rank = rankself.suit = suitdef __str__(self):reply = self.rank + self.suitreturn reply
  • 35.
    Guide to Programmingwith Python 35Overriding Base Class Methodsclass Unprintable_Card(Card):....def __str__(self):return "<unprintable>"• Unprintable_Card– Inherits all methods of Card– Overrides inherited method __str__()– Printed object displayed as <unprintable>• A derived class has no effect on a base class
  • 36.
    Guide to Programmingwith Python 36Invoking Base Class Methods• In overridden method, can incorporate inherited method’sfunctionality• Suppose we want to have a card that can be face up or facedown…class Positionable_Card(Card):def __init__(self, rank, suit, face_up = True):super(Positionable_Card, self).__init__(rank, suit)self.is_face_up = face_up• Superclass: Another name for a base class• Card is the superclass of Positionable_Card
  • 37.
    Guide to Programmingwith Python 37Invoking Base Class Methods(continued)• Incorporate inherited method’s functionality bycalling super()• Positionable_Card constructor invokes Cardconstructor and creates new attribute• super() lets you invoke the method of a superclass– First argument is the base class, Positionable_Card– Second is a reference to the object itself, self– Last is the superclass method you want to call withits parameters, __init__(rank, suit)
  • 38.
    Guide to Programmingwith Python 38Invoking Base Class Methods(continued)class Positionable_Card(Card):def __str__(self):if self.is_face_up:reply = super(Positionable_Card, self).__str__()else:reply = "XX"return repdef flip(self):self.is_face_up = not self.is_face_up• __str__() invokes superclass __str__() method ifcard is face up; otherwise, returns "XX"
  • 39.
    Guide to Programmingwith Python 39Using the Derived Classescard1 = Card("A", "c")card2 = Unprintable_Card("A", "d")card3 = Positionable_Card("A", "h")print card1 # Acprint card2 # <unprintable>print card3 # Ahcard3.flip()print card3 # XXplaying_cards3.py
  • 40.
    Guide to Programmingwith Python 40Understanding Polymorphism• Polymorphism: Aspect of object-orientedprogramming that allows you to send samemessage to objects of different classes, related byinheritance, and achieve different but appropriateresults for each object• When you invoke __str__() method ofUnprintable_Card object, you get different resultthan when you invoke the __str__() method of aCard object
  • 41.
    Guide to Programmingwith Python 41Creating Modules• Create, use, and even share your own modules• Reuse code– Could reuse the Card, Hand, and Deck classes fordifferent card games• Manage large projects– Professional projects can be hundreds of thousandsof lines long– Would be nearly impossible to maintain in one file
  • 42.
    Guide to Programmingwith Python 42The Simple Game ProgramFigure 9.7: Sample run of the Simple Game programProgram uses functions and class from programmer-created module.
  • 43.
    Guide to Programmingwith Python 43Writing Modules• Write module as a collection of relatedprogramming components, like functions andclasses, in single file• File is just Python file with extension .py• Module imported using filename, just like built-inmodules
  • 44.
    Guide to Programmingwith Python 44Writing Modules (continued)games module is file games.pyclass Player(object):""" A player for a game. """def __init__(self, name, score = 0):self.name = nameself.score = scoredef __str__(self):reply = self.name + ":t" + str(self.score)return reply
  • 45.
    Guide to Programmingwith Python 45Writing Modules (continued)def ask_yes_no(question):"""Ask a yes or no question."""response = Nonewhile response not in ("y", "n"):response = raw_input(question).lower()return responsedef ask_number(question, low, high):"""Ask for a number within a range."""response = Nonewhile response not in range(low, high):response = int(raw_input(question))return response
  • 46.
    Guide to Programmingwith Python 46Writing Modules (continued)if __name__ == "__main__":print "You ran module but must 'import' it."raw_input("nnPress the enter key to exit.")• __name__ == "__main__" is true if file is run directly;is false if the file is imported as module• If games.py run directly, message displayed that thefile is meant to be importedgames.py
  • 47.
    Guide to Programmingwith Python 47Importing Modulesimport games, random• Import programmer-created module the same wayyou import a built-in module
  • 48.
    Guide to Programmingwith Python 48Using Imported Functions and Classesnum = games.ask_number(question = "How many?",low = 2, high = 5)...player = games.Player(name, score)...again = games.ask_yes_no("Play again? (y/n): ")• Use imported programmer-created modules thesame way as you use imported built-in modulessimple_game.py
  • 49.
    Guide to Programmingwith Python 49The Blackjack Game - ClassesTable 9.1: Blackjack classes
  • 50.
    Guide to Programmingwith Python 50The Blackjack Game – ClassHierarchyFigure 9.8: Blackjack classesInheritance hierarchy of classes for the Blackjack game
  • 51.
    Guide to Programmingwith Python 51The Blackjack Game - PseudocodeDeal each player and dealer initial two cardsFor each playerWhile the player asks for a hit and the player is not bustedDeal the player an additional cardIf there are no players still playingShow the dealer’s two cardsOtherwiseWhile the dealer must hit and the dealer is not bustedDeal the dealer an additional cardIf the dealer is bustedFor each player who is still playingThe player wins
  • 52.
    Guide to Programmingwith Python 52The Blackjack Game – Pseudocode(continued)OtherwiseFor each player who is still playingIf the player’s total is greater than the dealer’s totalThe player winsOtherwise, if the player’s total is less than the dealer’s totalThe player losesOtherwiseThe player pushesblackjack.py
  • 53.
    Guide to Programmingwith Python 53Summary• In object-oriented programming, objects can sendmessages to each other by invoking each other’smethods• Objects can be composed of other objects or havecollections of objects• Inheritance is an aspect of object-orientedprogramming that allows a new class to be basedon an existing one where the new classautomatically gets (or inherits) all of the methodsand attributes of the existing one
  • 54.
    Summary (continued)• Inheritancecan be used to create a morespecialized version of an existing class• A base class is a class upon which another isbased; it is inherited from by this other class (thederived class)• A derived class is a class that is based uponanother class; it inherits from this other class (abase class)• Superclass is another name for base classGuide to Programming with Python 54
  • 55.
    Guide to Programmingwith Python 55Summary (continued)• A derived class can define new methods andattributes in addition to the ones that it inherits• To override an inherited method is to redefine howthe method of a base class works in a derivedclass• When overriding a method, the new definition canhave completely different functionality than theoriginal definition or the new definition canincorporate the functionality of the original
  • 56.
    Guide to Programmingwith Python 56Summary (continued)• The super() function allows you to invoke themethod of a superclass• Polymorphism is an aspect of object-orientedprogramming that allows you to send the samemessage to objects of different classes, related byinheritance, and achieve different but appropriateresults for each object• You can write, import, and even share your ownmodules
  • 57.
    Summary (continued)• Youwrite a module as a collection of relatedprogramming components, like functions andclasses, in a single Python file• Programmer-created modules can be imported thesame way that built-in modules are, with an importstatement• You test to see if __name__ is equal to"__main__" to make a module identify itself assuchGuide to Programming with Python 57

[8]ページ先頭

©2009-2025 Movatter.jp