Presentation is loading. Please wait.

Presentation is loading. Please wait.

COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris

Similar presentations


Presentation on theme: "COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris"— Presentation transcript:

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

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

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

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

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

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

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, …

8 Examples of data types (II) Temperature: –Same operations as for dates – Can define many average temperatures –Display formats are Celsius and Fahrenheit

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

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

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

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, …

13 Creating a new data type Two step process –Defining properties of the new object class Myobject –Create specific objects—instances—of that class x =Myobject( )

14 A very simple class (I) # person.py class Person """ defines a person """

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.name = '' self.birthdate = ''

16 A very simple class (III) def display(self) print('%s born on %s' % (self.name, self.birthdate))

17 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)

18 Rewriting display def display(self) print(str(self))

19 A better initialization def __init__(self, name = '', birthdate = '') self.name = name self.birthdate = birthdate

20 Controlling access Preventing inconsistent updates – setters Hiding private functions and variables –_ _ notation

21 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

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

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

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

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

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)

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)

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

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

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

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

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

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)

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

35 CONCLUSION

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

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

38 A last thought


Download ppt "COSC 1306—COMPUTER SCIENCE AND PROGRAMMING DATA ABSTRACTION Jehan-François Pâris"

Similar presentations


Ads by Google