21
Chapter 19-21 Chapter 19-21 Object Oriented Object Oriented Programming (OOP) Programming (OOP) CSC1310 Fall 2009 CSC1310 Fall 2009

Chapter 19-21 Object Oriented Programming (OOP) CSC1310 Fall 2009

Embed Size (px)

Citation preview

Chapter 19-21Chapter 19-21Object Oriented Object Oriented Programming (OOP)Programming (OOP)

CSC1310 Fall 2009CSC1310 Fall 2009

Objects as ModelsObjects as Models

Code is object-based.object-based. A program can be thought of as a model of

reality, with objects in the program representing physical objects.

Properties of objects: StateState (information stored within the object) BehaviorBehavior (operations that can be performed on

the object)

Example 1: Ball-point PenExample 1: Ball-point Pen The statestate of a ball-point pen with a retractable

point can be represented by two values: Is the point of the pen exposed? How much ink remains in the pen?

OperationsOperations on a pen include: Press the button at the end of the pen. Move the pen with the point held against a sheet of

paper. Replace the pen’s cartridge. Determine how much ink remains in the pen.

Example 2: Bank AccountExample 2: Bank Account

A statestate of a bank account includes the account number, the balance, the transactions performed on the account since it was opened, and so forth.

OperationsOperations on a bank account include: Deposit money into an account. Withdraw money from the account. Check the balance in the account. Close the account.

Example 3: CarExample 3: Car The statestate of a car includes the amount of fluids

in the car, the state of the tires, and even the condition of each part in the car.

For programming purposes, we can focus on just a few elements of the state: Is the engine on? How much fuel remains in the car’s tank?

OperationsOperations on a car include: Start the engine. Drive a specified distance.

Artificial ObjectsArtificial Objects

Nearly every “real-world” object can be modeled within a program.

Programmers also work with artificial objects that don’t correspond to objects in the physical world (mathematical objects: function, fraction, data record)

Like all objects, these artificial objects have state and behavior.

What is OOPWhat is OOP Python OOP is entirely optional! To qualify as being truly object-orientedobject-oriented objects

generally need to also participate in something called an inheritance hierarchy.

•InheritanceInheritance is a mechanism of code customization and reuse. It is a way to form new classes (instances of which are called objectsobjects) using classes that have already been defined.

What is OOPWhat is OOP PolymorphismPolymorphism means that meaning of operation

depends on the object being operated on. EncapsulationEncapsulation means packaging in Python: methods

and operators implement behavior; data hiding is a convention by default.

Why ClassesWhy Classes ClassClass is for implementing new kind of objects (state+behavior). Multiple InstancesMultiple Instances

Class = factory for generating objects. When class is called: new object is generated with its namespace. It has access to

class attributes, but keeps own data. Customization via InheritanceCustomization via Inheritance

Classes are extended by redefining their attributes outside class itself (namespace hierarchy) Operator OverloadingOperator Overloading

New class can implement built-in type operations.

Attribute Inheritance Attribute Inheritance SearchSearch Object.attributeObject.attribute:”find the firstfirst occurrence of attributeattribute by

looking in objectobject, and all classes above it, from bottom to top and left to right”.

To find an attribute, search a tree InheritanceInheritance: objects lower in a tree inherit attributes of

the objects higher in a tree

ClassesClasses - instance’s factory: provide default behavior

Instances Instances – concrete items: record data that varies per specific object.

Class treeClass treesuperclasses (parents)superclasses (parents)

subclasssubclass

Search is bottom-up: subclass may overrideoverride parent’s behavior, by redefining the attribute (for, example C1.x)

I2 “inherits” w from C3. I1.x, I2.x get from C1. I1.z, I2.z find z in C2. I2.name finds name in I2.

•Classes and instances are namespacesnamespaces. •Objects in class tree have “automatically-search” links to other namespace objects.

Coding the Class TreeCoding the Class Tree

classclass statement generates a new classclass <name>(superclass,…):class <name>(superclass,…): data=value #shared class datadata=value #shared class data def <method>(self,…): # Methodsdef <method>(self,…): # Methods self.status=dataself.status=data Each time a class is called, new instance is created. Instances are automatically linked to the class they are

created from Classes are linked to their superclasses. Left-to-right

order in parenthesis gives the order in tree.

Coding the Class TreeCoding the Class Treeclassclass C2: def x(selfself): print self.account def z(selfself,data): self.acc=dataclass class C3:

def w(selfself,data): self.acc+=data def z(selfself,data): self.acc-=dataclassclass C1 (C2,C3): def x(selfself,data): self.acc-=data def y(selfself, time): print “at ”+time+”:”+self.name +” has ”+ str(self.acc)I1=C1()I1=C1()I1.name=“O’Reily”I1.z(123)I1.y(“09/10/08”)I2=C2()I2=C2()

SelfSelf

defdef inside class is called as methodmethod Method automatically receives a special first argument

– self self - which provides a handle back to the instance to be processed.

classclass C1: def setname(selfself,name): self.name=name def printname(self): print self.name I1=C1(); I2=C1(); I1=C1(); I2=C1(); I1.setname(“Genry”); I2.setname(“Garry”)I1.printname(); I2.printname()

When method assigns to self attributes, it creates or changes an attribute of the instance being processed.

__init____init__

If coded and inherited, __init__, __init__ is called automatically each time an instance is generated (constructorconstructor).

Ensure that attributes are always set in instances without requiring extra calls.

classclass C1: def __init____init__(self, name): self.name=name def printname(self): print self.name I1=C1(“Genry”); I2=C1(“Garry”)I1=C1(“Genry”); I2=C1(“Garry”)I1.printname(); I2.printname()

Class Objects: Default Class Objects: Default BehaviorBehavior The classclass statement creates a class object and

assigns it a name. Assignments inside classclass statement make class

attributes. Class attributes provide object state and behavior:

Record state and behavior to be shared among instances

Methods process instances.classclass C1: state=value def __init__(selfself,name): self.name=name def printName(self): print self.name

Instance Objects: Concrete Instance Objects: Concrete ItemsItems Calling a class object makes a new instance object.

Each instance object inherits class attributes and gets its own namespace.

Assignments to attributes of selfself in methods make per-instance attributes.

Example 1Example 1

x.data=“change explicitly”x.newAttr=“less common:)”

Hierarchy of ClassesHierarchy of Classes

Subclasses allow to change default behavior without

changing component in place. Subclasses allow to have different implementation of

the same method depending on the object. Subclass may replace inherited attributes completely,

provide attributes that superclass expects to find, extend superclass methods.

Classes inherit attributes from their superclasses listed in parenthesis in the header of classclass.

Instances inherit attributes from all accessible classes. Each object.attrributeobject.attrribute invokes a new search. Logic changes are made by subclassingsubclassing, not by

changing superclasses.

Example2Example2

Specialization of the second class is external for the first, it does not affect it.

Calling Superclass Calling Superclass ConstructorConstructor

__init____init__ is looked up by inheritance If subclass constructor need to guarantee that superclass constructor runs too, it needs explicitly call it.class Parent: def __init__(self, x):…

class Child(Parent): def __init__(self, x,y): Parent.__init__(self,x) … Without explicit call, subclass constructor replaces superclass constructor completely.