Guide to Programming with Python Chapter Eight Part
















![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](https://slidetodoc.com/presentation_image_h/de4f07b246e8013aa6b44d2d83babea1/image-17.jpg)








- Slides: 25

Guide to Programming with Python 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

Lecture 1 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 Puppyobject def initself self name self color Two More Special Methods class Puppy(object): def __init__(self): self. name = [] self. color](https://slidetodoc.com/presentation_image_h/de4f07b246e8013aa6b44d2d83babea1/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 classy_critter. py 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