Guide to Programming with Python

Slides:



Advertisements
Similar presentations
General OO Concepts Objectives For Today: Discuss the benefits of OO Programming Inheritance and Aggregation Abstract Classes Encapsulation Introduce Visual.
Advertisements

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.
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.
Object-Oriented PHP (1)
Object-oriented Programming Concepts
Lilian Blot Announcements The TPOP problem class this afternoon:  group 1 should come at 3.30pm and group 2 at 4pm. Teaching Evaluation Form  week 9.
Guide to Programming with Python
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
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.
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris
CPSC 231: Classes and Objects You will learn how to define new types of variables that can have custom attributes and capabilities slide 1.
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
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.
Classes and Class Members Chapter 3. 3 Public Interface Contract between class and its clients to fulfill certain responsibilities The client is an object.
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.
Writing Classes (Chapter 4)
Chapter 11 Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
Chapter 12 Object Oriented Design.  Complements top-down design  Data-centered view of design  Reliable  Cost-effective.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Session 18 What are programs for? Classes and Objects.
Guide to Programming with Python Week 11 Chapter Nine Inheritance Working with multiple objects.
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
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 (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Object Oriented Programming In Python
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Introduction to Classes Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg.
INTRO2CS Tirgul 8 1. What We’ll Be Seeing Today  Introduction to Object-Oriented Programming (OOP).  Using Objects  Special methods 2.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
Object-Orientated Design (Summary)
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Object-Oriented Programming Concepts
Guide to Programming with Python
Chapter 7 Object-Oriented Programming
Object Oriented Programming in Python: Defining Classes
CPSC 231: Classes and Objects
COMPSCI 107 Computer Science Fundamentals
Object-Oriented Programming (OOP) in Python
Topics Procedural and Object-Oriented Programming Classes
CS-104 Final Exam Review Victor Norman.
Chapter 8 Analysis & Modeling
Lecture VI Objects The OOP Concept Defining Classes Methods
Creating and Deleting Instances Access to Attributes and Methods
Object Oriented Programming in Python Session -3
Chapter 3 Introduction to Classes, Objects Methods and Strings
Object Oriented Programming in Python
LECTURE 2: The Object Model
Guide to Programming with Python Book is by Michael Dawson
Ruby Classes.
Tonga Institute of Higher Education
CIS16 Application Development and Programming using Visual Basic.net
Object-Oriented PHP (1)
A Level Computer Science Topic 6: Introducing OOP
Programming For Big Data
Chapter 9 Introduction To Classes
Migrating to Object-Oriented Programs
Object-Oriented Design AND CLASS PROPERTIES
Anatomy of a class Part I
Presentation transcript:

Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game

More on OOP Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions”, and data rather than logic (from searchSOA.com) An object is a software bundle of related attributes and behavior (methods) A class is a blueprint or prototype from which objects are created Each object is capable of receiving messages, processing data, and sending messages to other objects (or client codes) and can be viewed as an independent module with a distinct role or functionality

Who Are You (PLTL exercise) class Person(object): total = 0 #class attribute def __init__(self, name="Tom", age=20, location="Bloomington"): self.name = name self.age = age self.location = location Person.total += 1 def talk(self): print "Hi, I am", self.name, "and I am", self.age, "years old" def __str__(self): return "Hi, I am " + self.name + " and I am " + str(self.age) + " years old" print "Before creating instances: Person.total=", Person.total aperson = Person() print "Hi, I am", aperson.name, "and I am", aperson.age, "years old” aperson.talk() print aperson ruby = Person("Ruby", 21) print "Hi, I am", ruby.name, "and I am", ruby.age, "years old” ruby.talk() print ruby print "Now Person.total=", Person.total

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

Private vs Public Attributes and 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

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 crit1._Critter__mood #instance._classname__variable Pseudo-encapsulation cannot really protect data from hostile code 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 crit1._Critter__private_method()works 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

Using Get Methods class Critter(object): ... def get_name(self): return self.__name crit = Critter("Poochie") print crit.get_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 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. ” crit = Critter("Poochie") crit.set_name("Randolph") Set method: Sets an attribute, often private, to a value; by convention, name starts with "set”, e.g., set_name()

Using Properties (Optional) 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 (Optional) >>> print crit.name Randolph >>> crit.name = "Sammy" Name change successful. Sammy >>> crit.name = "" Critter's name can't be empty string. Guide to Programming with Python

Respect Privacy Classes Objects Write methods (e.g., get & set 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

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

Examples The Critter Caretaker Program Super Dictionary Program

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