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

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.
Classes & Objects Computer Science I Last updated 9/30/10.
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
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 7 Object-Oriented Programming.
1.11 Introduction to OOP academy.zariba.com 1. Lecture Content 1.What is OOP and why use it? 2.Classes and objects 3.Static classes 4.Properties, fields.
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.
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.
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
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)
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.
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.
11 Chapter 11 Object-Oriented Databases Database Systems: Design, Implementation, and Management 4th Edition Peter Rob & Carlos Coronel.
Chapter 6 Object-Oriented Java Script JavaScript, Third Edition.
James Tam Classes and Objects You will learn how to define new types of variables.
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.
1 Computer Science of Graphics and Games MONT 105S, Spring 2009 Session 18 What are programs for? Classes and Objects.
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.
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.
Object Oriented Programming
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.
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
Object Oriented Programming Session # 03.  Abstraction: Process of forming of general and relevant information from a complex scenarios.  Encapsulation:
Guide to Programming with Python Chapter Six Functions: The Tic-Tac-Toe Game.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
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.
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
Object-Oriented Programming (OOP) in Python
Topics Procedural and Object-Oriented Programming Classes
CS-104 Final Exam Review Victor Norman.
Anatomy of a class Part I
Chapter 3 Introduction to Classes, Objects Methods and Strings
Guide to Programming with Python
Object Oriented Programming in Python
Guide to Programming with Python Book is by Michael Dawson
Ruby Classes.
Object-Oriented PHP (1)
A Level Computer Science Topic 6: Introducing OOP
Migrating to Object-Oriented Programs
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 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 Python4

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 Python5

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 Python6

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 Python7

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 Python8

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 Python9

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 Python10

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 Python11

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() 12

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 Python13

Using Properties (Optional) >>> print crit.name Randolph >>> crit.name = "Sammy" Name change successful. >>> print crit.name Sammy >>> crit.name = "" Critter's name can't be empty string. Guide to Programming with Python14

Respect Privacy  Classes –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 Python15

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 Python16

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 Python18