Presentation is loading. Please wait.

Presentation is loading. Please wait.

Guide to Programming with Python Book is by Michael Dawson

Similar presentations


Presentation on theme: "Guide to Programming with Python Book is by Michael Dawson"— Presentation transcript:

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

2 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

3 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

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

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

6 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 puppy1 = Puppy("Max", "brown") puppy1.bark() puppy2 = Puppy("Ruby", "black") puppy2.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

7 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

8 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

9 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

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

11 Invoking a Method Any Critter object has method talk()
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

12 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

13 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

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

15 Accessing Attributes Assessing attributes using methods: talk()
class Critter(object): ... def talk(self): print "Hi. I'm", self.name, "\n" crit1.talk() print crit1.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

16 Printing an Object (How?)
class Critter(object): ... def __str__(self): rep = "Critter object\n" rep += "name: " + self.name + "\n" return rep print crit1 __str__ is a special method that returns string representation of object (sample code) Guide to Programming with Python

17 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']

18 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

19 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

20 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 crit1.total #the instance #crit1.total += 1 # won’t work; can't assign new value to a class attribute through instance

21 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

22 Invoking a Static Method
... crit1 = Critter("critter 1") crit2 = Critter("critter 2") crit3 = Critter("critter 3") 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

23 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

24 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

25 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

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

27 More on OOP Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions”, and data rather than logic (from searchSOA.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

28 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

29 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

30 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

31 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

32 Accessing Private Attributes
class Critter(object): ... def talk(self): print "\nI'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 crit1.__mood won’t work Technically possible to access through object, but shouldn’t crit1._Critter__mood #instance._classname__variable Pseudo-encapsulation cannot really protect data from hostile code Guide to Programming with Python

33 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

34 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 crit1.__private_method() won’t work Technically possible to access through object, but shouldn’t crit1._Critter__private_method()works Guide to Programming with Python

35 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

36 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

37 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()

38 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

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

40 Respect Privacy Classes Objects
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

41 New-Style and Old-Style Classes
class Critter(object): # new-style class class Critter: # 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

42 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

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

44 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

45 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

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

47 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

48 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

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

50 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

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

52 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

53 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

54 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

55 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

56 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

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

58 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

59 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

60 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

61 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

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

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

64 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

65 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

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

67 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

68 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 random.randrange(10) 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!) What else have you tried?

69 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

70 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("\n\nPress 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 )

71 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

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

73 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 sys.path.append('/home/yye/lib/python')

74 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/ Top-level package __init__.py Initialize the sound package formats/ Subpackage for file format conversions __init__.py wavread.py wavwrite.py ... effects/ Subpackage for sound effects echo.py import sound.effects.echo #or from sound.effects import echo

75 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 If the player’s total is greater than the dealer’s total Otherwise, if the player’s total is less than the dealer’s total The player loses The player pushes

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

77 The Blackjack Game - Classes
Table 9.1: Blackjack classes Guide to Programming with Python

78 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

79 Key OOP Concepts Inheritance Encapsulation
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)

80 All done! Guide to Programming with Python


Download ppt "Guide to Programming with Python Book is by Michael Dawson"

Similar presentations


Ads by Google