520 likes | 978 Views
Introduction to Object Oriented Programming (OOP). Angel de Vicente PostDoc Software Support Ext. 387 angelv@iac.es. Summary. Paradigms of programming Introduction to OOP Examples of OOP with Python. Paradigms of Programming. Procedural (FORTRAN, Pascal, C, …) Functional (LISP, …)
E N D
Introduction to Object Oriented Programming (OOP) Angel de Vicente PostDoc Software Support Ext. 387 angelv@iac.es
Summary • Paradigms of programming • Introduction to OOP • Examples of OOP with Python
Paradigms of Programming • Procedural (FORTRAN, Pascal, C, …) • Functional (LISP, …) • Logic (PROLOG, …) • Object-oriented (Smalltalk, …) • Visual (Visual Basic, …) • …
Procedural Programming while ( programming == art ) { incr( pleasure ); decr( bugs ); incr( portability ); incr( maintainability ); incr( quality ); incr( salary ); } // live happily ever after
O-O Vs. Procedural • Procedural paradigm • Program defines data and then calls subprogram to act on the data • Object paradigm • Program creates objects that encapsulate the data and procedures that operate on the data
Some OO Languages • Smalltalk -- a radical change in programming languages • Eiffel -- a language with assertions • C++ -- is much more than a better C • Java -- the dial-tone of the Internet • DLP -- introduces logic into object orientation • But also… • Python, Perl, IDL, …
Benefits of OOP • OO = encapsulation + inheritance • Modularity -- autonomous entities, cooperation through exchanges of messages • Deferred commitment -- the internal workings of an object can be redefined without changing other parts of the system • Reusability -- refining classes through inheritance • Naturalness -- object-oriented analysis/design, modeling • Maintainability
An object is like a black box. The internal details are hidden. Identifying objects and assigning responsibilities to these objects. Objects communicate to other objects by sending messages. Messages are received by the methods of an object. What Is Object Oriented Programming?
Object Terminology • Objects -- packet containing data and procedures • Class -- template for creating objects • Instance -- an object that belongs to a class • Methods -- deliver service • Message -- request to execute a method • Encapsulation -- information hiding by objects • Inheritance -- allowing the reuse of class spec.S class • Hierarchy -- tree structure inheritance relations • Polymorphism -- to hide different implementations • Aggregation -- to include classes as part of other classes
What Is an Object? • Tangible things as a car, printer, ... • Roles as employee, boss, ... • Incidents as flight, overflow, ... • Interactions as contract, sale, ... • Specifications as colour, shape, …
Objects in the Real World • Objects have attributes and interact with each other by passing messages. Can I order this sofa set Alex 1 Robinson Rd $2,000 Lawrence 15 $200 No problem. It’s $199, sir.
Objects Differentiate Each Other by Their Attributes. Can I have this dinning table Can I order this sofa set Alex 1 Robinson Rd $2,000 Julia 18 Nanyang Ave $1,000
Similar Objects Can Be Grouped Into a Group name address budget placeOrder Customers
Objects Can Be Categorized Into Different Groups People in Furniture Shop name employeeNo commission takeOrder name address budget placeOrder Customers SalesPerson
Objects and Classes Interpretation in the real world Representation in the model An object represents anything in the real world that can be distinctly identified. Object An object has a unique identity, a state, and behaviors A class represents a set of objects with similar characteristics and behaviors. These objects are called instance of the class A class characterizes the structure of states and behaviors that are shared by all its instances. Class
Objects and Classes (2) • Objects in programming • alex, julia and lawrence are objects: • identity - object reference • state - value of attributes • behavior - definition of methods • Customer and SalesPerson are classes: • Objectsalex and julia are instances of classCustomer and object lawrence is an instance of class SalesPerson • Objects interact through message passing • Customer and SalesPerson classes are the specialization of PeopleInFurnitureShop class
The Two Parts of an Object Object = Data + Methods or to say the same differently: An object has the responsibility to know and the responsibility to do. = +
Basic Terminology:Behaviour and Messages • The most important aspect of an object is its behaviour (the things it can do). A behaviour is initiated by sending a message to the object (usually by calling a method).
Telephone.call(2416881) Message Components • The object to receive the message • The method to execute • Any other necessary information needed by the method (parameters) Object.method(parameters)
#include<string> #include<iostream> class Person{ char name[20]; int yearOfBirth; public: void displayDetails() { cout << name << " born in " << yearOfBirth << endl; } //... }; Example: The Person class private data public processes
Basic Terminology • Abstraction is the representation of the essential features of an object. These are ‘encapsulated’ into an abstract data type. • Encapsulation is the practice of including in an object everything it needs hidden from other objects. The internal state is usually not accessible by other objects.
Encapsulation - Real Life • Bank machine • Hidden data • account balance • personal information • Interface • deposit, withdraw, transfer • display account information
Interaction Among Classes • A program is composed of multiple classes • Classes may contain references to other classes within the set of attributes or behaviours • Start in an application class (main) • construct one or more objects and call methods associated with those objects
Basic Terminology:Inheritance • Inheritance means that one class inherits the characteristics of another class.This is also called a “is a” relationship: A car is a vehicle A dog is an animal A teacher is a person
Inheritance • The inheriting class contains all the attributes and behaviours of the class it inherited from plus any attributes and behaviours it defines • The inheriting class can override the definition of existing methods by providing its own implementation • The code of the inheriting class consists only of the changes and additions to the base class
Inheritance Terminology • Class one above • Parent class, Super class • Class one below • Child class • Class one or more above • Ancestor class, Base class • Class one or more below • Descendent class
Why Use Inheritance? • Modular coding • less code, easier to understand • Code reuse • don’t break what is already working • easier updates • May not have access to modify the original source code • Polymorphism
Basic Terminology:Polymorphism • Polymorphism means “having many forms”. It allows different objects to respond to the same message in different ways, the response specific to the type of the object. E.g. the message displayDetails() in our furniture shop should give different results when send to a Customer or a SalesPerson.
Basic Terminology:Aggregation • Aggregation describes a “has a” relationship. One object is a part of another object. • We distinguish between composite aggregation (the composite “owns” the part) and shared aggregation (the part is shared by more than one composite). A car has wheels.
BankAccount SavingsAccount int acctNumClient acctHolderdouble balance double interestRatedouble accruedInterestTime lastBalanceChange BankAccount(Client info)void deposit(double amt)boolean withdraw(double amt)void printStatement() SavingsAccount(...)void updateIntRate(double rate)void deposit(double amt)boolean withdraw(double amt) ChequingAccount double minBalance ChequingAccount(…)boolean withdraw(double amt)double calcServiceFee() Inheritance, polymorphism and aggregation
The Two Steps of Object Oriented Programming • Making Classes: Creating, extending or reusing abstract data types. • Making Objects interact: Creating objects from abstract data types and defining their relationships.
Python simplest OO program! #!/usr/local/bin/python class House: pass my_house = House() my_house.number = 40 print "My house is", my_house.number [angelv@guinda Python]$ ./first.py My house is 40
Class constructors #! /usr/local/bin/python class House: def __init__(self, number, rooms, garden): self.number = number self.rooms = rooms self.garden = garden my_house = House(20, 1, 0) print "My house is number", my_house.number print "It has", my_house.rooms, "rooms" if my_house.garden: garden_text = "has" else: garden_text = "does not have" print "It", garden_text, "a garden" • [angelv@guinda Python]$ ./second.py • My house is number 20 • It has 1 rooms • It does not have a garden • [angelv@guinda Python]$
Example: Atom class class atom: def __init__(self,atno,x,y,z): self.atno = atno self.position = (x,y,z) def symbol(self): # a class method return Atno_to_Symbol[atno] def __repr__(self): # overloads printing return '%d %10.4f %10.4f %10.4f' % (self.atno, self.position[0], self.position[1],self.position[2]) >>> at = atom(6,0.0,1.0,2.0) >>> print at 6 0.0000 1.0000 2.0000 >>> at.symbol() 'C'
Atom class • Overloaded the default constructor • Defined class variables (atno,position) that are persistent and local to the atom object • Good way to manage shared memory: • instead of passing long lists of arguments, encapsulate some of this data into an object, and pass the object. • much cleaner programs result • Overloaded the print operator • We now want to use the atom class to build molecules...
Molecule Class class molecule: def __init__(self,name='Generic'): self.name = name self.atomlist = [] def addatom(self,atom): self.atomlist.append(atom) def __repr__(self): str = 'This is a molecule named %s\n' % self.name str = str+'It has %d atoms\n' % len(self.atomlist) for atom in self.atomlist: str = str + `atom` + '\n' return str
Using Molecule Class >>> mol = molecule('Water') >>> at = atom(8,0.,0.,0.) >>> mol.addatom(at) >>> mol.addatom(atom(1,0.,0.,1.)) >>> mol.addatom(atom(1,0.,1.,0.)) >>> print mol This is a molecule named Water It has 3 atoms 8 0.000 0.000 0.000 1 0.000 0.000 1.000 1 0.000 1.000 0.000 • Note that the print function calls the atoms print function • Code reuse: only have to type the code that prints an atom once; this means that if you change the atom specification, you only have one place to update.
Public and Private Data • Currently everything in atom/molecule is public, thus we could do something really stupid like • >>> at = atom(6,0.,0.,0.) • >>> at.position = 'Grape Jelly' that would break any function that used at.poisition • We therefore need to protect the at.position and provide accessors to this data • Encapsulation or Data Hiding • accessors are "gettors" and "settors" • Encapsulation is particularly important when other people use your class
Encapsulated Atom class atom: def __init__(self,atno,x,y,z): self.atno = atno self.__position = (x,y,z) #position is private def getposition(self): return self.__position def setposition(self,x,y,z): self.__position = (x,y,z) #typecheck first! def translate(self,x,y,z): x0,y0,z0 = self.__position self.__position = (x0+x,y0+y,z0+z)
Why Encapsulate? • By defining a specific interface you can keep other modules from doing anything incorrect to your data • By limiting the functions you are going to support, you leave yourself free to change the internal data without messing up your users • Write to the Interface, not the Implementation • Makes code more modular, since you can change large parts of your classes without affecting other parts of the program, so long as they only use your public functions
Specializing Inherited Methods class Super: def method(self): print ‘in Super.method’ def delegate(self): self.action() • Simple inheritance class Inheritor(Super): pass
Specializing Inherited Methods (2) class Super: def method(self): print ‘in Super.method’ def delegate(self): self.action() • Replacing behaviour class Replacer(Super): def method(self): print ‘in Replacer.method’
Specializing Inherited Methods (3) class Super: def method(self): print ‘in Super.method’ def delegate(self): self.action() • Extending behaviour class Extender(Super): def method(self): print ‘starting Extender.method’ Super.method(self) print ‘ending Extender.method’
Specializing Inherited Methods (4) class Super: def method(self): print ‘in Super.method’ def delegate(self): self.action() • Providing behaviour class Provider(Super): def action(self): print ‘in Provider.action’
Specializing Inherited Methods (5) • What we get… % python specialize.py Inheritor… in Super.method Replacer… in Replacer.method Extender… starting Extender.method in Super.method ending Extender.method Provider… in Provider.action
Conclusions • OOP is just another paradigm of programming • Features of OOP: encapsulation, abstraction, aggregation and inheritance. • Benefits of OOP are: modularity, reusability, naturalness and maintainability. • Syntax and OOP concepts quite simple. • Steps for OOP: making classes, creating objects and making them interact. • For beginners the most difficult part is the classes hierarchy design.