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

Slides:



Advertisements
Similar presentations
Python Objects and Classes
Advertisements

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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 9 Classes.
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
OOP - Object Oriented Programming Object Oriented Programming is an approach to programming that was developed to make large programs easier to manage.
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 11 Classes and Object- Oriented Programming.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
James Tam Classes and Objects You will learn how to define new types of variables.
Object Oriented Paradigm Programming Paradigms En Mohd Norafizal A.Aziz.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 8 Objects and Classes. 2 Motivations After learning the preceding chapters, you are capable of solving many programming problems using selections,
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Fundamentals of Python: From First Programs Through Data Structures
Guide to Programming with Python
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
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.
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
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.
1 Survey of Computer Science CSCI 110, Spring 2011 Lecture 14 Recursion.
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
11 Chapter 11 Object-Oriented Databases Database Systems: Design, Implementation, and Management 4th Edition Peter Rob & Carlos Coronel.
Guide to Programming with Python
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
Classes and Objects The basics. Object-oriented programming Python is an object-oriented programming language, which means that it provides features that.
Classes 1 COMPSCI 105 S Principles of Computer Science.
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
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,
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
Object Oriented Programing (OOP)
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?!
Object Oriented Programming In Python
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Basic Concepts of OOP.  Object-Oriented Programming (OOP) is a type of programming added to php5 that makes building complex, modular and reusable web.
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Exceptions and Handling
Object-Oriented Programming (OOP) in Python References: Chapter 8.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
OOP - Object Oriented Programming
Classes (Part 1) Lecture 3
Guide to Programming with Python
Object Oriented Programming
Object-Oriented Programming (OOP) in Python
Section 11.1 Class Variables and Methods
Lecture VI Objects The OOP Concept Defining Classes Methods
3 Fundamentals of Object-Oriented Programming
To Get Started Paper sheet
Guide to Programming with Python
Teach A-Level Computer Science: Object-Oriented Programming in Python
Week 3 Object-based Programming: Classes and Objects
Guide to Programming with Python Book is by Michael Dawson
Object-Oriented Programming
Presentation 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 Python2

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 Python5

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

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 Python8

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 Python9

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 Python10 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 Python11

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 Python12

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 13

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 Python14

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 Python15 (sample code)

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

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 Python17

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 Python18

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 19

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 20

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 Python21 classy_critter.py

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 Python22

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 Python23