Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes,...

Post on 24-Dec-2015

233 views 0 download

transcript

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

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#

Lecture 1

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 Objectsclass 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

6

The Simple Critter Programclass 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

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

Guide to Programming with Python 11

simple_critter.py

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 Attributesclass 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

14

Accessing Attributes

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 15

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

Guide to Programming with Python 16(sample code)

Two More Special Methodsclass 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 Attributeclass 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 Attributeclass 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 classprint crit1.total #the instance

#crit1.total += 1 # won’t work; can't assign new value to a class attribute through instance

20

Creating a Static Methodclass 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

...

crit1 = Critter("critter 1")

crit2 = Critter("critter 2")

crit3 = 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

classy_critter.py

Setting default valuesclass 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