COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris [email protected].
-
Upload
ursula-barber -
Category
Documents
-
view
224 -
download
0
Transcript of COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris [email protected].
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
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
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
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
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
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, …
Examples of data types (II)
• Temperature:– Same operations as for dates– Can define many average temperatures– Display formats are Celsius and Fahrenheit
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
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
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
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, …
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( )
A very simple class (I)
• # person.pyclass Person""" defines a person"""
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 = ''
A very simple class (III)
• def display(self) print('%s born on %s'
% (self.name, self.birthdate))
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)
Rewriting display
• def display(self) print(str(self))
A better initialization
• def __init__(self, name = '', birthdate = '')self.name = nameself.birthdate = birthdate
Controlling access
• Preventing inconsistent updates– setters
• Hiding private functions and variables–_ _ notation
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
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
A better example of getter (I)
• Want to create a class for points in a two dimensional space
(x, y)y-axis
x-axis
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))
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
• 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)
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)
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
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
Limitation of protection
• Protects against good faith mistakesbut not against malicious behavior
• Java solution is stronger– Variables can be declared public or private
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
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
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)
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
CONCLUSION
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
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
A last thought