Guide to Programming with Python Book is by

Guide to Programming with Python Book is by Michael Dawson https: //www. amazon. com/dp/1423901126/ Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods

Objectives § § § Create classes to define objects Write methods and create attributes for objects Instantiate objects from classes Restrict access to an object’s attributes Work with both new-style and old-style classes § The Critter Caretaker Program Guide to Programming with Python 2

Python Is Object-Oriented § Object-oriented programming (OOP): Methodology that defines problems in terms of objects that send messages to each other – dir(1) – In a game, a Missile object could send a Ship object a message to Explode § OOP not required, unlike Java and C# Guide to Programming with Python 3

Understanding Object-Oriented Basics § OOP allows representation of real-life objects as software objects (e. g. , a dictionary as an object) § Object: A single software unit that combines attributes and methods § Attribute: A "characteristic" of an object; like a variable associated with a kind of object § Method: A "behavior" of an object; like a function associated with a kind of object § Class: Code that defines the attributes and methods of a kind of object (A class is a collection of variables and functions working with these variables) 4

Fundamental Concepts of OOP § § § Information hiding Abstraction Encapsulation Modularity Polymorphism Inheritance Guide to Programming with Python 5

Creating Classes for Objects class Puppy(object): def __init__(self, name, color): self. name = name self. color = color def bark(self): print "I am", color, name puppy 1 = Puppy("Max", "brown") puppy 1. bark() puppy 2 = Puppy("Ruby", "black") puppy 2. bark() § Class: Code that defines the attributes and methods of a kind of object § Instantiate: To create an object; A single object is called an Instance 6

The Simple Critter Program class Critter(object): """A virtual pet""" def talk(self): print "Hi. I'm an instance of class Critter. ” # main crit = Critter() crit. talk() § Define class: – Class name, begin with capital letter, by convention – object: class based on (Python built-in type) § Define a method – Like defining a function – Must have a special first parameter, self, which provides way for a method to refer to object itself 7

Class methods & “self” parameter § Class methods have only one specific difference from ordinary functions--they must have an extra first name that has to be added to the beginning of the parameter list § You do not give a value for this parameter(self) when you call the method, Python will provide it. § This particular variable refers to the object itself, and by convention, it is given the name self. Guide to Programming with Python 8

Instantiating an Object crit = Critter() § Create new object with class name followed by set of parentheses – Critter() creates new object of class Critter § Can assign a newly instantiated object to a variable of any name – crit = Critter() assigns new Critter object to crit § Avoid using variable that's same name as the class name in lowercase letters Guide to Programming with Python 9

Creating Multiple Objects crit 1 = Critter() crit 2 = Critter() § Creating multiple objects is easy § Two objects created here § Each object is independent, full-fledged critter Guide to Programming with Python 10

Invoking a Method crit. talk() § Any Critter object has method talk() § crit. talk() invokes talk() method of Critter object crit § Prints string "Hi. I'm an instance of class Critter. " simple_critter. py Guide to Programming with Python 11

Using Constructors § Constructor: A special method that is automatically invoked right after a new object is created § Usually write one in each class § Usually sets up the initial attribute values of new object in constructor Guide to Programming with Python 12

Creating a Constructor def __init__(self): print "A new critter has been born!" § New Critter object automatically announces itself to world § __init__ – Is special method name – Automatically called by new Critter object Guide to Programming with Python 13

Initializing Attributes class Critter(object): def __init__(self, name): self. name = name. . . crit 1 = Critter("Poochie”) § Can have object’s attributes automatically created and initialized through constructor (Big convenience!) § self – first parameter in every instance method receives reference to new Critter object name receives "Poochie" self. name = name creates the attribute name for object and sets to "Poochie" crit 1 gets new Critter object – self – – – 14

Accessing Attributes class Critter(object): . . . def talk(self): print "Hi. I'm", self. name, "n". . . crit 1. talk() print crit 1. name § Assessing attributes using methods: talk() – Uses a Critter object’s name attribute – Receives reference to the object itself into self § Accessing Attributes Directly Guide to Programming with Python 15

Printing an Object (How? ) class Critter(object): . . . def __str__(self): rep = "Critter objectn" rep += "name: " + self. name + "n" return rep. . . print crit 1 a special method that returns string representation of object § __str__ is Guide to Programming with Python (sample code) 16
![Two More Special Methods class Puppy(object): def __init__(self): self. name = [] self. color Two More Special Methods class Puppy(object): def __init__(self): self. name = [] self. color](http://slidetodoc.com/presentation_image_h2/80ee62e8daa9ab562c97ee873395a236/image-17.jpg)
Two More Special Methods class Puppy(object): def __init__(self): self. name = [] self. color = [] def __setitem__(self, name, color): self. name. append(name) self. color. append(color) def __getitem__(self, name): if name in self. name: return self. color[self. name. index(name)] else: return None dog = Puppy() dog['Max'] = 'brown' dog['Ruby'] = 'yellow’ print "Max is", dog['Max'] 17

Using Class Attributes and Static Methods § Class attribute: A single attribute that’s associated with a class itself (not an instance!) § Static method: A method that’s associated with a class itself § Class attribute could be used for counting the total number of objects instantiated, for example § Static methods often work with class attributes Guide to Programming with Python 18

Creating a Class Attribute class Critter(object): total = 0 § total = 0 creates class attribute total set to 0 § Assignment statement in class but outside method creates class attribute § Assignment statement executed only once, when Python first sees class definition § Class attribute exists even before single object created § Can use class attribute without any objects of class in existence Guide to Programming with Python 19

Accessing a Class Attribute class Critter(object): total = 0 def status(): print "Total critters", Critter. total status = staticmethod(status) def __init__(self, name): Critter. total += 1 print Critter. total #the class print crit 1. total #the instance #crit 1. total += 1 # won’t work; can't assign new value to a class attribute through instance 20

Creating a Static Method class Critter(object): . . . def status(): print "Total critters", Critter. total status = staticmethod(status) § status() – Is static method – Doesn't have self in parameter list because method will be invoked through class not object § staticmethod() – Built-in Python function – Takes method and returns static method 21

Invoking a Static Method. . . crit 1 = Critter("critter 1") crit 2 = Critter("critter 2") crit 3 = Critter("critter 3") Critter. status() § Critter. status() – Invokes static method status() defined in Critter – Prints a message stating that 3 critters exist – Works because constructor increments class attribute total, which status() displays Guide to Programming with Python 22

Setting default values class Person(object): def __init__(self, name="Tom", age=20): self. name = name self. age = age def talk(self): print "Hi, I am", self. name def __str__(self): return "Hi, I am " + self. name one = Person(name="Yuzhen", age = "forever 20") print one two = Person() print two Guide to Programming with Python 23

Summary § Object-oriented Programming (OOP) is a methodology of programming where new types of objects are defined § An object is a single software unit that combines attributes and methods § An attribute is a “characteristic” of an object; it’s a variable associated with an object (“instance variable”) § A method is a “behavior” of an object; it’s a function associated with an object § A class defines the attributes and methods of a kind of object Guide to Programming with Python 24

Summary (continued) § Each instance method must have a special first parameter, called self by convention, which provides a way for a method to refer to object itself § A constructor is a special method that is automatically invoked right after a new object is created § A class attribute is a single attribute that’s associated with a class itself § A static method is a method that’s associated with a class itself Guide to Programming with Python 25

Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game

More on OOP § Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions”, and data rather than logic (from search. SOA. com) § An object is a software bundle of related attributes and behavior (methods) § A class is a blueprint or prototype from which objects are created § Each object is capable of receiving messages, processing data, and sending messages to other objects (or client codes) and can be viewed as an independent module with a distinct role or functionality

Who Are You class Person(object): total = 0 #class attribute def __init__(self, name="Tom", age=20, location="Bloomington"): self. name = name self. age = age self. location = location Person. total += 1 def talk(self): print "Hi, I am", self. name, "and I am", self. age, "years old" def __str__(self): return "Hi, I am " + self. name + " and I am " + str(self. age) + " years old" print "Before creating instances: Person. total=", Person. total aperson = Person() print "Hi, I am", aperson. name, "and I am", aperson. age, "years old” aperson. talk() print aperson ruby = Person("Ruby", 21) print "Hi, I am", ruby. name, "and I am", ruby. age, "years old” ruby. talk() print ruby print "Now Person. total=", Person. total

Understanding Object Encapsulation § Client code should – Communicate with objects through method parameters and return values – Avoid directly altering value of an object’s attribute § Objects should – Update their own attributes – Keep themselves safe by providing indirect access to attributes through methods Guide to Programming with Python 29

Private vs Public Attributes and Methods § Public: Can be directly accessed by client code § Private: Cannot be directly accessed (easily) by client code § Public attribute or method can be accessed by client code § Private attribute or method cannot be (easily) accessed by client code § By default, all attributes and methods are public § But, can define an attribute or method as private Guide to Programming with Python 30

Creating Private Attributes class Critter(object): def __init__(self, name, mood): self. name = name # public attribute self. __mood = mood # private attribute § name – Created as any attribute before – Public attribute (default) § __mood – Private attribute – Two underscore characters make private attribute – Begin any attribute with two underscores to make private Guide to Programming with Python 31

Accessing Private Attributes class Critter(object): . . . def talk(self): print "n. I'm", self. name print "Right now I feel", self. __mood, "n" § Private attributes – Can be accessed inside the class – Can’t be accessed directly through object • crit 1. __mood won’t work – Technically possible to access through object, but shouldn’t crit 1. _Critter__mood #instance. _classname__variable – Pseudo-encapsulation cannot really protect data from hostile code Guide to Programming with Python 32

Creating Private Methods class Critter(object): . . . def __private_method(self): print "This is a private method. " § Like private attributes, private methods defined by two leading underscores in name § __private_method() is a private method Guide to Programming with Python 33

Accessing Private Methods class Critter(object): . . . def public_method(self): print "This is a public method. " self. __private_method() § Like private attributes, private methods – Can be accessed inside class – Can’t be accessed directly through object • crit 1. __private_method() won’t work – Technically possible to access through object, but shouldn’t crit 1. _Critter__private_method()works Guide to Programming with Python 34

Controlling Attribute Access § Instead of denying access to an attribute, can limit access to it § Example: client code can read, but not change attribute § Properties can manage how attribute is accessed or changed Guide to Programming with Python 35

Using Get Methods class Critter(object): . . . def get_name(self): return self. __name. . . crit = Critter("Poochie") print crit. get_name() § Get method: A method that gets the value of an attribute, which is often private; by convention, name starts with “get” § get_name() provides indirect access to __name Guide to Programming with Python 36

Using Set Methods class Critter(object): . . . def set_name(self, new_name): if new_name == "": print "Critter's name can't be empty string. " else: self. __name = new_name print "Name change successful. ” crit = Critter("Poochie") crit. set_name("Randolph") § Set method: Sets an attribute, often private, to a value; by convention, name starts with "set”, e. g. , set_name() 37

Using Properties (Optional) class Critter(object): . . . name = property(get_name, set_name) § Property: An interface that allows indirect access to an attribute by wrapping access methods around dot notation § property() function – Takes accessor methods and returns a property – Supply with get and set methods for controlled access to private attribute – Supply only get method for “read-only” property Guide to Programming with Python 38

Using Properties (Optional) >>> print crit. name Randolph >>> crit. name = "Sammy" Name change successful. >>> print crit. name Sammy >>> crit. name = "" Critter's name can't be empty string. Guide to Programming with Python 39

Respect Privacy § Classes – Write methods (e. g. , get & set methods) so no need to directly access object’s attributes – Use privacy only for attributes and methods that are completely internal to operation of object § Objects – Minimize direct reading of object’s attributes – Avoid directly altering object’s attributes – Never directly access object’s private attributes or methods Guide to Programming with Python 40

New-Style and Old-Style Classes class Critter(object): class Critter: # new-style class # old-style class § New-style class: A class that is directly or indirectly based on the built-in object § Old-style class: A class that is not based on object, directly or indirectly § New-style classes – Introduced in Python 2. 2 – Significant improvements over old-style – Create instead of old-style classes whenever possible Guide to Programming with Python 41

Summary § Public attributes and methods can be directly accessed by client code § Private attributes and methods cannot (easily) be directly accessed by client code § A get method gets the value of an attribute; by convention, its name starts with “get” § A set method sets an attribute to a value; by convention, its name starts with “set” Guide to Programming with Python 42

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 44

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 45

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

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 47

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 48

Inheritance Example: Animal Class class Animal(object): def __init__(self, name): 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!' # Constructor 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 animals = [Cat('Missy'), Cat('Mr. Bojangles'), Dog('Lassie')] for animal in animals: print animal. talk() + ' I am ' + animal. get_name() 49

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 50

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!' 51

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 52

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 53

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 54

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 55

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 56

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 Derived. Class(Base 1, Base 2, Base 3): . . . § Python interprets this by applying the depth-first, left-to right rule: if an attribute is not found in Derived. Class, it is searched in Base 1, then (recursively) in the base classes of Base 1, and only if it is not found there, it is searched in Base 2, and so on) 57

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 58

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 59

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 60

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 61

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 card 1 = Card(”A", ”d") # A Card object with rank "A" and suit "d" is the ace of diamonds print card 1 62

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

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

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 65

Guide to Programming with Python Chapter Nine Working with/Creating Modules

Creating Modules § Create, use, and even share your own modules § Reuse code – Could reuse the Card, Hand, and Deck classes for different card games § Manage large projects – Professional projects can be hundreds of thousands of lines long – Would be nearly impossible to maintain in one file 67

Using Modules § Module imported using filename, just like built-in modules § Import programmer-created module the same way you import a built-in module import random. randrange(10) What else have you tried? from random import * randrange(10) (import * operation may not work very well on Windows platforms, where the filesystem does not always have accurate information about the case of a filename!) 68

Writing Modules § Write module as a collection of related programming components, like functions and classes, in a single file § File is just Python file with extension. py (games module is file games. py) class Player(object): """ A player for a game. """ def __init__(self, name, score = 0): self. name = name self. score = score def __str__(sefl): return "name=" + name + " score=" + str(score) def ask_yes_no(question): """Ask a yes or no question. """ response = None while response not in ("y", "n"): response = raw_input(question). lower() return response 69

if __name == "__main__" class Player(object): """ A player for a game. """ def __init__(self, name, score = 0): . . . if __name__ == "__main__": test = Player("Tom", 100) print tet raw_input("nn. Press the enter key to exit. ") § Why do I need to do this? To make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file (__name__ == "__main__" is true ) 70

Using Imported Functions and Classes num = games. ask_number(question = "How many? ", low = 2, high = 5) player = games. Player(name, score) § Use imported programmer-created modules the same way as you use imported built-in modules 71

What’s are Defined in a Module? § The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings: import sys dir(sys)

Module Not Found? § The Module Search Path – When a module named spam is imported, the interpreter searches for a file named spam. py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. § Modules are searched in the list of directories given by the variable sys. path import sys. path. append('/home/yye/lib/python')

Packages § Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A. B designates a submodule named B in a package named A. sound/ __init__. py formats/ __init__. py wavread. py wavwrite. py. . . effects/ __init__. py echo. py import sound. effects. echo #or from sound. effects import echo Top-level package Initialize the sound package Subpackage for file format conversions Subpackage for sound effects

The Blackjack Game - Pseudocode Deal each player and dealer initial two cards For each player While the player asks for a hit and the player is not busted Deal the player an additional card If there are no players still playing Show the dealer’s two cards Otherwise While the dealer must hit and the dealer is not busted Deal the dealer an additional card If the dealer is busted For each player who is still playing The player wins Otherwise For each player who is still playing If the player’s total is greater than the dealer’s total The player wins Otherwise, if the player’s total is less than the dealer’s total The player loses Otherwise The player pushes 75

The Blackjack Game – Class Hierarchy Figure 9. 8: Blackjack classes Inheritance hierarchy of classes for the Blackjack game 76

The Blackjack Game - Classes Table 9. 1: Blackjack classes Guide to Programming with Python 77

Summary § You can write, import, and even share your own modules § You write a module as a collection of related programming components, like functions and classes, in a single Python file § Programmer-created modules can be imported the same way that built-in modules are, with an import statement § You test to see if __name__ is equal to "__main__" to make a module identify itself as such 78

Key OOP Concepts § Inheritance – Inheriting vs. overriding (Implementing a new one or adding) – Polymorphism means that the same message can be sent to objects of different classes related by inheritance and achieve different and appropriate results. For example, when Human or Comput object calls flip_or_take() methods, they do things differently. Polymorphism enables objects of different types to be substituted (e. g. , the human-vs-compute Flip game to human-vs-human Flip game). § Encapsulation – The inclusion within a program object of all the resources needed for the object to function: the methods and the data to hide the details of the inner workings from the client code. – Encapsulation is a principle of abstraction -- a concept or idea not associated with any specific instance (OOP attempts to abstract both data and code)

All done! Guide to Programming with Python 80
- Slides: 80