Guide to Programming with Python

Slides:



Advertisements
Similar presentations
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
Advertisements

Python Objects and Classes
Object-Oriented Programming
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
From datetime import * class StopWatch(object): def __init__(self): now = datetime.now() self.hr = now.hour self.min = now.minute self.sec = now.second.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 11 Classes and Object- Oriented Programming.
VBA Modules, Functions, Variables, and Constants
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 7 Object-Oriented Programming.
Classes and Objects, Part 1 Victor Norman CS104. Reading Quiz, Q1 A class definition define these two elements. A. attributes and functions B. attributes.
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
I210 review (for final exam) Fall 2011, IUB. What’s in the Final Exam Multiple Choice (5) Short Answer (5) Program Completion (3) Note: A single-sided.
Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
Chapter 10 Classes. Review of basic OOP concepts  Objects: comprised of associated DATA and ACTIONS (methods) which manipulate that data.  Instance:
1 Survey of Computer Science CSCI 110, Spring 2011 Lecture 14 Recursion.
Chapter 5 - Writing a Problem Domain Class Definition1 Chapter 5 Writing a Problem Domain Class Definition.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Chapter 10: Writing Class Definitions Visual Basic.NET Programming: From Problem Analysis to Program Design.
Comments are for people Header comments supply basic information about the artifact.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
Classes CS 21a: Introduction to Computing I First Semester,
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
Classes and Objects The basics. Object-oriented programming Python is an object-oriented programming language, which means that it provides features that.
1 Chapter 8 – Classes and Object: A Deeper Look Outline 1 Introduction 2 Implementing a Time Abstract Data Type with a Class 3 Class Scope 4 Controlling.
Object-Oriented Application Development Using VB.NET 1 Chapter 6 Writing a Problem Domain Class Definition.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
Chapter 10 Classes and Objects In-Depth. Chapter 10 A class provides the foundation for creating specific objects, each of which shares the general attributes,
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
Chapter 3 (B) 3.5 – 3.7.  Variables declared in a function definition’s body are known as local variables and can be used only from the line of their.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Introduction to Defining Classes
Object Oriented Programing (OOP)
Copyright © 2002 W. A. Tucker1 Chapter 10 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Object Oriented Programming
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Introduction to Object-Oriented Programming Lesson 2.
Section 6.1 CS 106 Victor Norman IQ Unknown. The Big Q What do we get by being able to define a class?! Or Do we really need this?!
Clearly Visual Basic: Programming with Visual Basic 2008 Chapter 27 I Love this Class.
Object Oriented Programming In Python
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
Class Fundamentals BCIS 3680 Enterprise Programming.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Classes (Part 1) Lecture 3
Guide to Programming with Python
COMPSCI 107 Computer Science Fundamentals
Topics Procedural and Object-Oriented Programming Classes
CS-104 Final Exam Review Victor Norman.
Chapter 3: Using Methods, Classes, and Objects
Classes.
Lecture VI Objects The OOP Concept Defining Classes Methods
Chapter 3 Introduction to Classes, Objects Methods and Strings
Guide to Programming with Python
Defining Classes and Methods
Guide to Programming with Python Book is by Michael Dawson
Object Oriented Programming in java
Presentation transcript:

Guide to Programming with Python Chapter Eight Software Objects: The Critter Caretaker Program

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

Chapter Project: The Critter Caretaker Program Figure 8.1: Sample run of the Critter Caretaker program You get to name your very own critter. Guide to Programming with Python

Chapter Project: The Critter Caretaker Program (continued) Figure 8.2: Sample run of the Critter Caretaker program If you neglect your critter, it will have a mood change for the worse. Guide to Programming with Python

Chapter Project: The Critter Caretaker Program (continued) Figure 8.3: Sample run of the Critter Caretaker program With the proper care, your critter will return to its sunny mood. Guide to Programming with Python

Understanding Object-Oriented Basics Object-oriented Programming (OOP): A methodology of programming where new types of objects are defined 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 Guide to Programming with Python

Understanding Object-Oriented Basics (continued) Method: A "behavior" of an object; like a function associated with a kind of object Instance: A single object Instantiate: To create an object Class: Code that defines the attributes and methods of a kind of object Guide to Programming with Python

Creating Classes, Methods, and Objects OOP allows representation of real-life objects as software objects Spacecraft objects Attribute: Energy level Method: Fire weapons Each object has similar structure (energy level and fire weapons) but each has unique values (one might have energy level of 3, another energy level of 10) Guide to Programming with Python

The Simple Critter Program Figure 8.4: Sample run of the Simple Critter program The Critter object’s talk() method makes the critter greet the world. Guide to Programming with Python

The Simple Critter Program (continued) class Critter(object): """A virtual pet""" def talk(self): print "Hi. I'm an instance of class Critter." # main crit = Critter() crit.talk() Guide to Programming with Python

Defining a Class Class name should begin with a capital letter class Critter(object): """A virtual pet""" class keyword Class name should begin with a capital letter Critter Parentheses contain the class this class is based on object, fundamental built-in type Docstring, describes kind of objects Guide to Programming with Python

Defining a Method Define a method like a function def talk(self): print "Hi. I'm an instance of class Critter." Define a method like a function When you define it “inside” a Class it is a method Every instance method must have a special first parameter, called self by convention Special first parameter provides way for a method to refer to object itself Am I Ship A, with an energy level of 10, or am I Ship B, with an energy level of 3? Consult self! Guide to Programming with Python

Instantiating an Object crit = Critter() Create new object of the specified class (use 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 (well, maybe) Guide to Programming with Python

Invoking a Method Every Critter object has a talk()method crit.talk() Every Critter object has a talk()method crit.talk() invokes the talk() method of the 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 You might give a spaceship 10 units of energy to start with, that it then uses up by flying around and getting shot at Guide to Programming with Python

The Constructor Critter Program Figure 8.5: Sample run of the Constructor Critter program Two separate critters are created. Each says hi. 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

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

Using Attributes Can have object’s attributes automatically created and initialized through constructor Big convenience; done often Guide to Programming with Python

The Attribute Critter Program Figure 8.6: Sample run of the Attribute Critter program Each Critter object has attribute name it uses when it says hi. Guide to Programming with Python

Initializing Attributes class Critter(object): def __init__(self, name): self.name = name self First parameter in every instance method Automatically receives reference to the object invoking method Allows method to get at the object itself to access object’s attributes or methods (or even create new attributes, as we are doing here in __init__) Guide to Programming with Python

Initializing Attributes (continued) class Critter(object): def __init__(self, name): self.name = name ... crit1 = Critter("Poochie") self receives reference to new Critter object name receives "Poochie" self.name = name creates the attribute name for this object and sets it to "Poochie" crit1 gets new Critter object named "Poochie" Guide to Programming with Python

Accessing Attributes Uses a Critter object’s name attribute class Critter(object): ... def talk(self): print "Hi. I'm", self.name, "\n" crit1.talk() talk() method Uses a Critter object’s name attribute Receives reference to the object itself into self Prints Hi. I'm Poochie by accessing attribute name of particular object through self.name Guide to Programming with Python

Accessing Attributes (continued) class Critter(object): def __init__(self, name): self.name = name ... crit1 = Critter("Poochie") print crit1.name print crit1.name prints string "Poochie" Can access object attribute outside class with dot notation – but should avoid Guide to Programming with Python

Printing an Object Another special method (sample code) class Critter(object): ... def __str__(self): rep = "Critter object\n" rep += "name: " + self.name + "\n" return rep print crit1 __str__ Another special method Returns string representation of object attribute_critter.py Guide to Programming with Python

Using Class Attributes and Static Methods Class attribute: A single attribute that’s associated with a class itself Static method: A method that’s associated with a class itself Class attribute could be used for number of objects instantiated, for example How many spaceships are there? Static methods often work with class attributes Guide to Programming with Python

The Classy Critter Program Figure 8.7: Sample run of the Classy Critter program Total number of objects in class attribute, displayed by static method Guide to Programming with Python

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

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 ... print crit1.total Guide to Programming with Python

Accessing a Class Attribute (continued) Access class attribute with dot notation - both inside class or out Critter.total += 1 #inside class print Critter.total #outside class Can access class attribute through class instance print crit1.total But can't assign new value through instance crit1.total += 1 # won’t work as might expect Guide to Programming with Python

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

Creating a Static Method (continued) Built-in Python function Takes method and returns static method status = staticmethod(status) Takes method status() and returns static method Assigns static method to status and that name is used to call the static method Guide to Programming with Python

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

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

Using Private Attributes and Private 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

The Private Critter Program Figure 8.8: Sample run of the Private Critter program Object’s Private attribute and private method are indirectly accessed. Guide to Programming with Python

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

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

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

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

Respecting an Object’s Privacy crit = Critter(name = "Poochie", mood = "happy") crit.talk() crit.public_method() Code accesses only public methods Public methods access private methods and attributes private_critter.py semi-private_critter.py Guide to Programming with Python

Understanding When to Implement and Respect Privacy Classes Write 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

Understanding 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

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

The Property Critter Figure 8.9: Sample run of the Property Critter program Property controls access to Critter object’s attribute for its name. Guide to Programming with Python

Using Get Methods class Critter(object): ... def get_name(self): return self.__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

Using Get Methods (continued) >>> crit = Critter("Poochie") >>> print crit.get_name() Poochie get_name() returns string for Critter object’s name Guide to Programming with Python

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." name = property(get_name, set_name) Guide to Programming with Python

Using Set Methods (continued) >>> crit.set_name("") Critter’s name can’t be empty string. >>> crit.set_name("Randolph") Name change successful. >>> print crit.get_name() Randolph Set method: Sets an attribute, often private, to a value; by convention, name starts with "set" set_name() allows a value to be assigned to private variable __name; imposes restriction that the value cannot be the empty string Guide to Programming with Python

Using Properties 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

Using Properties (continued) >>> print crit.name Randolph >>> crit.name = "Sammy" Name change successful. Sammy >>> crit.name = "" Critter's name can't be empty string. property_critter.py critter_caretaker.py 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

Summary (continued) 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” A property wraps access (get and set) methods around dot notation syntax Guide to Programming with Python