cosc 1306—computer science and programming data abstraction jehan-françois pâris


Post on 25-Dec-2015




0 download

Embed Size (px)


  • Slide 1
  • Slide 2
  • 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
  • Slide 3
  • 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
  • Slide 4
  • 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
  • Slide 5
  • 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
  • Slide 6
  • 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
  • Slide 7
  • 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,
  • Slide 8
  • Examples of data types (II) Temperature: Same operations as for dates Can define many average temperatures Display formats are Celsius and Fahrenheit
  • Slide 9
  • 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
  • Slide 10
  • 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
  • Slide 11
  • 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
  • Slide 12
  • 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,
  • Slide 13
  • Creating a new data type Two step process Defining properties of the new object class Myobject Create specific objectsinstancesof that class x =Myobject( )
  • Slide 14
  • A very simple class (I) # class Person """ defines a person """
  • Slide 15
  • 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.birthdate = ''
  • Slide 16
  • A very simple class (III) def display(self) print('%s born on %s' % (, self.birthdate))
  • Slide 17
  • Adding a __str__ method def __str__(self) # converts a given instance of Myclass # into a string return '%s born on %s' % (, self.age)
  • Slide 18
  • Rewriting display def display(self) print(str(self))
  • Slide 19
  • A better initialization def __init__(self, name = '', birthdate = '') = name self.birthdate = birthdate
  • Slide 20
  • Controlling access Preventing inconsistent updates setters Hiding private functions and variables _ _ notation
  • Slide 21
  • Setters Allow to control updates def set_birthdate(self, date) : # check that date is well formed # say, mm/dd/yyyy if ok : return
  • Slide 22
  • Getters Provides a way to access instance attributes and even to compute some on the fly @property # this is a decorator def name(self) : return self._age Note that age was renamed _age
  • Slide 23
  • A better example of getter (I) Want to create a class for points in a two dimensional space (x, y) y-axis x-axis
  • Slide 24
  • 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))
  • Slide 25
  • 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
  • Slide 26
  • 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)
  • Slide 27
  • A better example of getter (IV) With "@property" decorator @property def rho(self) : import mat return math.sqrt(self.x**2 + self.y^2) @property def theta(self) : import math return math.atan2(self.y, self.x)
  • Slide 28
  • 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
  • Slide 29
  • 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 __birthdate can only be accessed outside of its class definition by using the full name p._Person.__birthdate
  • Slide 30
  • Limitation of protection Protects against good faith mistakes but not against malicious behavior Java solution is stronger Variables can be declared public or private
  • Slide 31
  • 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
  • Slide 32
  • 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
  • Slide 33
  • 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)
  • Slide 34
  • 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
  • Slide 35
  • Slide 36
  • 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
  • Slide 37
  • 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
  • Slide 38
  • A last thought


View more >