260 likes | 282 Views
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
E N D
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
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
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)
Fundamental Concepts of OOP • Information hiding • Abstraction • Encapsulation • Modularity • Polymorphism • Inheritance Guide to Programming with Python
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
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
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
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 tocrit • Avoid using variable that's same name as the class name in lowercase letters Guide to Programming with Python
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
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
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
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
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 • selfreceives reference to new Critterobject • namereceives"Poochie" • self.name = namecreates the attribute namefor object and sets to "Poochie" • crit1gets new Critterobject
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 aCritterobject’snameattribute • Receives reference to the object itself into self • Accessing Attributes Directly Guide to Programming with Python
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
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']
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
Creating a Class Attribute class Critter(object): total = 0 • total = 0creates class attribute totalset 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
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
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
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 inCritter • 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
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
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
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