Transcript
Page 1: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

COSC 1306—COMPUTER SCIENCE AND PROGRAMMING

DATA ABSTRACTION

Jehan-François Pâ[email protected]

Page 2: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Module Overview

• We will learn how people can write safer code through data abstraction– Also called object-oriented programming

• Main concepts common to all modern programming languages– Java, C++, C#, Objective C, MS Visual Basic– Not C

Page 3: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

The big idea

• Let programmers define– Their own data types with their

own operations– Like all the built-in types we have seen– Operations specific to numbers, strings, lists,

sets and so on• Cannot concatenate sets:

must do a union

Page 4: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Advantages (I)

• Implement and forget:– Write the operations then use them as if they

were built-in• Better code organization:

– Functions related to a given data type are kept together• Much easier to modify

Page 5: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Advantages (II)

• Data abstraction:– Makes possible to hide implementation details

• Prevent incorrect data operations– Such as adding temperatures

• Can update an internal representation without impacting the users of the data type

Page 6: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Example

• Maintaining a schedule– list of pairs [time, event] sorted by ascending

times• Easiest solution is using a linked list:

– Append new entries at the end and sort the list each time

– Works well as long as list is short– For very long lists should use a heap

Page 7: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Examples of data types (I)

• Date:– Can create, display and modify a date– Can define difference between two dates

• Sole arithmetic operation on dates– Can test for equality– Can define multiple display formats:

• 11/28/2011, Monday, November 28, 2011, …

Page 8: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Examples of data types (II)

• Temperature:– Same operations as for dates– Can define many average temperatures– Display formats are Celsius and Fahrenheit

Page 9: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Examples of data types (III)

• Account balance:– Can create accounts and display their balance– Do deposits and withdrawals– Credit interests– Debit management fees– Close the account

Page 10: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Examples of data types (IV)

• Appointment schedule:– Can create a new (empty) schedule– Add an appointment (time + reason)– Display an appointment– Reschedule an appointment– Change its reason– Look for time conflicts– Display a schedule– Clear whole schedule

Page 11: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

The main idea

• Once all possible meaningful operations on an object have been defined, we should prevent programmers to perform any other operations– Should not be able to

• Add temperatures• Mess with structure of schedule

Page 12: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Another advantage

• We will hide the details of the implementation– So we can change it without having to modify

the programs using the object.

• Same idea as moving to a new car technology but keeping the same user interface:– Wheel, gas (?) pedal, brake, transmission

controls, emergency brake, …

Page 13: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Creating a new data type

• Two step process– Defining properties of the new object

• class Myobject<class definition>

– Create specific objects—instances—of that class• x =Myobject( )

Page 14: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A very simple class (I)

• # person.pyclass Person""" defines a person"""

Page 15: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A very simple class (II)

• def __init__(self)# invoked each time you create a new # instance of class person# self refers to the instance being created

self.name = ''self.birthdate = ''

Page 16: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A very simple class (III)

• def display(self) print('%s born on %s'

% (self.name, self.birthdate))

Page 17: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Adding a __str__ method

• def __str__(self)# converts a given instance of Myclass# into a string

return '%s born on %s' % (self.name, self.age)

Page 18: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Rewriting display

• def display(self) print(str(self))

Page 19: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A better initialization

• def __init__(self, name = '', birthdate = '')self.name = nameself.birthdate = birthdate

Page 20: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Controlling access

• Preventing inconsistent updates– setters

• Hiding private functions and variables–_ _ notation

Page 21: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Setters

• Allow to control updates

• def set_birthdate(self, date) :# check that date is well formed# say, mm/dd/yyyy…if ok :

return self.date

Page 22: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Getters• Provides a way to access instance attributes and

even to compute some on the fly

• @property # this is a decoratordef name(self) :

return self._age

• Note that age was renamed _age

Page 23: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A better example of getter (I)

• Want to create a class for points in a two dimensional space

(x, y)y-axis

x-axis

Page 24: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

The starting point

• class Point : def __init__(self, x, y) : self.x = x self.y = y

p = Point(1,0)q = Point(1,1)print('q = (%f, %f)' % (q.x, q.y))

Page 25: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A better example of getter (II)

• Points can also be identified through their polar coordinates (rho and theta)

(x, y)y-axis

x-axis

rho

theta

Page 26: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

• Could add to the class Point functions such as• def rho(self) :

import mat return math.sqrt(self.x**2 + self.y**2)

• def theta(self) : import math return math.atan2(self.y, self.x)

• Can now access Point.rho( ) and Point.theta( )

A better example of getter (III)

Page 27: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A better example of getter (IV)

• With "@property" decorator• @property

def rho(self) : import mat return math.sqrt(self.x**2 + self.y^2)

• @propertydef theta(self) : import math return math.atan2(self.y, self.x)

Page 28: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A better example of getter (V)

• Can now write things such as– module = p.rho– angle = p.theta

but not– p.rho = x– p.theta = alpha

• See demo

Page 29: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Hiding methods and attributes

• An attribute or a function are protected against unwanted accesses by making them private– Prefix their names with two underscores:

• A attribute/function named __birthdatecan only be accessed outside of its class definition by using the full namep._Person.__birthdate

Page 30: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Limitation of protection

• Protects against good faith mistakesbut not against malicious behavior

• Java solution is stronger– Variables can be declared public or private

Page 31: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Inheritance

• Big idea is building a new class by adding features to an exiting class– Class Student(Person)

…• Means new class Student extends class

Person• Can also say that class Student inherits from

class Person

Page 32: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

An example (I)

• Suppose we want to add our own implementation of complex numbers– Share many properties with points in a

two-dimensional space– String representation is different

• (x, y) becomes x + iy

Page 33: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

An example (II)

• class Complex(Point) : def __str__(self) if self.x == 0 : if self.y == 0 return '0' else : return '%fi' % self.y else: if self.y == 0 : return '%f' % self.x else : return '%f +%fi' % (self.x,self.y)

Page 34: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

An example (III)

• Had to consider four cases for output format– x = 0 and y = 0

print 0– x ≠ 0 and y = 0

print x– x= 0 and y ≠ 0

print iy– x ≠ 0 and y ≠ 0

print x + iy

Page 35: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

CONCLUSION

Page 36: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Python

• Very powerful language– Many things to learn?

• Will learn most of them when you need to use them

– Powerful constructs simplify programmer's task

Page 37: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

Programming in Python

• Most important step is organizing your thoughts

• Pseudo-code is an important tool– Looks like Python but contains steps in

English• if strings contains a newline :

remove it

Page 38: COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris jfparis@uh.edu

A last thought


Top Related