Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes...

29
Centre for Computer Technology ICT115 ICT115 Object Object Oriented Oriented Design and Design and Programming Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information and Communication Technology Box Hill Institute of TAFE

Transcript of Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes...

Centre for Computer Technology

ICT115ICT115Object Oriented Object Oriented

Design and Design and Programming Programming

Week 2Intro to Classes

Richard Salomon and Umesh PatelCentre for Information and

Communication TechnologyBox Hill Institute of TAFE

April 19, 2023April 19, 2023 SlideSlide22 Copyright Box Hill Institute

Contents at a GlanceContents at a Glance

Introduction to classes Introduction to classes Methods Methods Introduction to ObjectsIntroduction to ObjectsUML UML Program Example Program Example

April 19, 2023April 19, 2023 SlideSlide33 Copyright Box Hill Institute

ClassClassClass - A blueprint for an object.Class - A blueprint for an object.

Contains attributes of Contains attributes of each object that it defineseach object that it defines

Attributes Attributes Data (aka fields) of a class Data (aka fields) of a class

- describe the state of an object- describe the state of an objectbehaviours or methods of a classbehaviours or methods of a class

- describe what an object can do - describe what an object can do

April 19, 2023April 19, 2023 SlideSlide44 Copyright Box Hill Institute

Data type Data type – describes the type of data held in a field – describes the type of data held in a field

Instance Instance - an object that is used by an application - an object that is used by an application

Method Method - set of instruction describing the - set of instruction describing the

operations performed by an object operations performed by an object - essentially a function that belongs to a class - essentially a function that belongs to a class

April 19, 2023April 19, 2023 SlideSlide55 Copyright Box Hill Institute

Naming of ClassesNaming of ClassesMust begin with a letter of an alphabet Must begin with a letter of an alphabet Can contain only letters, digits, or Can contain only letters, digits, or

underscores underscores Can not be a keyword or literalCan not be a keyword or literalCase sensitiveCase sensitiveStart with an upper case letter and then Start with an upper case letter and then

use lower case letters, with the first use lower case letters, with the first character of a new word capitalised character of a new word capitalised e.g. Person, MotorVehicle e.g. Person, MotorVehicle

April 19, 2023April 19, 2023 SlideSlide66 Copyright Box Hill Institute

Example 2.1. Creating a ClassExample 2.1. Creating a Class

#!/usr/bin/python#!/usr/bin/python

# Filename: simplestclass.py# Filename: simplestclass.py

class Person:class Person:

pass # An empty blockpass # An empty block

p = Person() # Create an instance Person p = Person() # Create an instance Person

print p print p

April 19, 2023April 19, 2023 SlideSlide77 Copyright Box Hill Institute

How It WorksHow It Works We create a new class using the class statement We create a new class using the class statement

followed by the name of the class. An indented block of followed by the name of the class. An indented block of statements which form the body of the class follows. statements which form the body of the class follows. In this case, we have an empty block which is indicated In this case, we have an empty block which is indicated using the using the passpass statement. statement.

Next, we create an object or an instance of this class Next, we create an object or an instance of this class using an empty constructor, which is the name of the using an empty constructor, which is the name of the class followed by a pair of parentheses. class followed by a pair of parentheses.

For our verification, we confirm the type of the variable For our verification, we confirm the type of the variable by simply printing it. It tells us that we have an instance by simply printing it. It tells us that we have an instance of the Person class in the __main__ module.of the Person class in the __main__ module.

Notice that the address of the computer memory where Notice that the address of the computer memory where your object is stored is also printed. The address will your object is stored is also printed. The address will have a different value on your computer since Python have a different value on your computer since Python can store the object wherever it finds space. can store the object wherever it finds space.

April 19, 2023April 19, 2023 SlideSlide88 Copyright Box Hill Institute

Output Output

>>>>>>

<__main__.Person instance at 0xf6fcb18c> <__main__.Person instance at 0xf6fcb18c>

>>> >>>

April 19, 2023April 19, 2023 SlideSlide99 Copyright Box Hill Institute

Constructor MethodsConstructor Methods

All class definitions include a constructor All class definitions include a constructor method to create objectsmethod to create objects

methodName = ClassName()methodName = ClassName()ClassName() is a null constructorClassName() is a null constructorNULL constructor – without arguments NULL constructor – without arguments

April 19, 2023April 19, 2023 SlideSlide1010 Copyright Box Hill Institute

Example 2.2. Using Object MethodsExample 2.2. Using Object Methods#!/usr/bin/python#!/usr/bin/python# Filename: method.py# Filename: method.pyclass Person:class Person:

def sayHi(self):def sayHi(self):print 'Hello, how are you?‘ print 'Hello, how are you?‘

p = Person() # instantiate a person named pp = Person() # instantiate a person named pp.sayHi()p.sayHi()

# This short example can also be written as # This short example can also be written as Person().sayHi()Person().sayHi()

April 19, 2023April 19, 2023 SlideSlide1111 Copyright Box Hill Institute

Output Output and and How It WorksHow It Works

>>>>>>

Hello, how are you?Hello, how are you?

>>>>>>

Here we see the self in action. Notice that Here we see the self in action. Notice that the sayHi method takes no parameters but the sayHi method takes no parameters but still has the self in the function definition. still has the self in the function definition.

April 19, 2023April 19, 2023 SlideSlide1212 Copyright Box Hill Institute

The selfThe self Class methods have only one specific difference Class methods have only one specific difference

from ordinary functions - they must have an from ordinary functions - they must have an extra first name that has to be added to the extra first name that has to be added to the beginning of the parameter list, but you beginning of the parameter list, but you do not do not give a value for this parameter when you call the give a value for this parameter when you call the method. method.

Python will provide it. Python will provide it. This particular variable refers to the object itself, This particular variable refers to the object itself,

and by convention, it is given the name and by convention, it is given the name selfself..

April 19, 2023April 19, 2023 SlideSlide1313 Copyright Box Hill Institute

The __init__ method There are many method names which have

special significance in Python classes.

The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object. Notice the double underscore both in the beginning and at the end in the name.

The __init__ method is a constructor. The __init__ method is a constructor.

April 19, 2023April 19, 2023 SlideSlide1414 Copyright Box Hill Institute

Example 2.3. Using the __init__ method

#!/usr/bin/python

# Filename: class_init.py

class Person:

def __init__(self, aName):

self.name = aName

def sayHi(self):

print 'Hello, my name is', self.name

p = Person('Swaroop')

p.sayHi()

April 19, 2023April 19, 2023 SlideSlide1515 Copyright Box Hill Institute

Output

>>>

Hello, my name is Swaroop

>>>

April 19, 2023April 19, 2023 SlideSlide1616 Copyright Box Hill Institute

Class and Object VariablesClass and Object Variables Class variables Class variables are shared in the sense that they are are shared in the sense that they are

accessed by all objects (instances) of that class.accessed by all objects (instances) of that class. There is There is only one copy of the class variableonly one copy of the class variable and and

when any one object makes a changewhen any one object makes a change to a class to a class variable, variable, the change is reflected in all the other the change is reflected in all the other instancesinstances as well. as well.

Object variables Object variables are owned by each individual are owned by each individual object/instance of the class. In this case, each object object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared has its own copy of the field i.e. they are not shared and are not related in any way to the field by the and are not related in any way to the field by the same name in a different instance of the same class. same name in a different instance of the same class.

RememberRemember this simple this simple differencedifference between class and between class and objectobject variables. variables.

An example will make this easy to understand. An example will make this easy to understand.

April 19, 2023April 19, 2023 SlideSlide1717 Copyright Box Hill Institute

Example 2.4. Using Class and Object Variables

See the filename: objvar.py found in the Wk02-Examples folder and

Observe its operation

April 19, 2023April 19, 2023 SlideSlide1818 Copyright Box Hill Institute

Example 2.4 detailsExample 2.4 details In Example 2.4. , we also see the use of docstrings for In Example 2.4. , we also see the use of docstrings for

classes as well as methods. classes as well as methods. We can access the class docstring at runtime We can access the class docstring at runtime

using Person.__doc__ and using Person.__doc__ and the method docstring as Person.sayHi.__doc__ the method docstring as Person.sayHi.__doc__

Just like the __init__ method, there is another special Just like the __init__ method, there is another special method __del__ which is called when an object is going method __del__ which is called when an object is going to die to die i.e. it is no longer being used i.e. it is no longer being used

The __del__ method returns the resources used by the The __del__ method returns the resources used by the object, such as its allocated memory, back to the system object, such as its allocated memory, back to the system for reusing. for reusing.

April 19, 2023April 19, 2023 SlideSlide1919 Copyright Box Hill Institute

The __del__ method The The __del__ method is run when the object is no longer __del__ method is run when the object is no longer

in usein use and and there is there is no guarantee no guarantee whenwhen that method will that method will be run. be run.

If you want to explicitly kill an object, you just have to call If you want to explicitly kill an object, you just have to call the __del__ method. the __del__ method.

Calling the __del__ method can create some bad side Calling the __del__ method can create some bad side effects, so it is best to avoid it. effects, so it is best to avoid it.

The __del__ method is analogous to the concept of a The __del__ method is analogous to the concept of a destructor. destructor.

April 19, 2023April 19, 2023 SlideSlide2020 Copyright Box Hill Institute

Attribute characteristics Attribute characteristics

All All class membersclass members (including the data members) (including the data members) are are publicpublic and all the methods are and all the methods are virtual virtual in in Python.Python.

One exception: If you use data members with One exception: If you use data members with names using the names using the double underscore prefix double underscore prefix such such as __privateVar, Python uses name-mangling to as __privateVar, Python uses name-mangling to effectively make it a private variable. effectively make it a private variable.

April 19, 2023April 19, 2023 SlideSlide2121 Copyright Box Hill Institute

Attribute characteristicsAttribute characteristics

The convention followed is that any variable that The convention followed is that any variable that is to be used only within the class or object is to be used only within the class or object should begin with an underscore, all other should begin with an underscore, all other names are public and can be used by other names are public and can be used by other classes/objects. Remember that this is only a classes/objects. Remember that this is only a convention and is not enforced by Python convention and is not enforced by Python (except for the double underscore prefix).(except for the double underscore prefix).

April 19, 2023April 19, 2023 SlideSlide2222 Copyright Box Hill Institute

Method TypesMethod Types

Accessor or getterAccessor or getter a method that gets data from an a method that gets data from an

objectobjectMutator or setter Mutator or setter

a method that sets data in an object a method that sets data in an object

Custom MethodCustom Methoda method to perform a specific user a method to perform a specific user defined task defined task

April 19, 2023April 19, 2023 SlideSlide2323 Copyright Box Hill Institute

Message – request for a methodMessage – request for a methodMessage sendingMessage sending

objects send (and receive) messagesobjects send (and receive) messagesto interact with each otherto interact with each other

[ This is really just a method call ] [ This is really just a method call ]

Re-useRe-useonce written and tested, once written and tested, objects and classes can be used objects and classes can be used in other applications in other applications

April 19, 2023April 19, 2023 SlideSlide2424 Copyright Box Hill Institute

EncapsulationEncapsulationcontaining or packaging data containing or packaging data and methods in a classand methods in a class

Information (data) hidingInformation (data) hidingblack box approachblack box approachi.e. no need to publish detailsi.e. no need to publish details

April 19, 2023April 19, 2023 SlideSlide2525 Copyright Box Hill Institute

Overloaded MethodsOverloaded Methods

methods with methods with same name but different same name but different formatsformats (data types) are called (data types) are called overloadedoverloaded methods methods

method signature identifies the specific method signature identifies the specific method used method used

April 19, 2023April 19, 2023 SlideSlide2626 Copyright Box Hill Institute

UMLUML UML – Unified Modelling LanguageUML – Unified Modelling Language

DiagramsDiagrams Use Case DiagramUse Case Diagram functionalityfunctionality Class diagramClass diagram static structurestatic structure Object diagramObject diagram State chart DiagramState chart Diagram dynamic behaviourdynamic behaviour Collaboration diagramsCollaboration diagrams object object interaction interaction Activity diagramsActivity diagrams dynamic naturedynamic nature Component Component DeploymentDeployment

April 19, 2023April 19, 2023 SlideSlide2727 Copyright Box Hill Institute

UML Diagrams UML Diagrams Rectangle describes classes and objectsRectangle describes classes and objects Lines describe relationshipsLines describe relationships Symbols describe accessibility and strength of Symbols describe accessibility and strength of

relationshipsrelationships+ public + public - private- private# protected # protected default (no symbol) default (no symbol)

LinksLinksinheritanceinheritanceassociationassociationaggregationaggregation

April 19, 2023April 19, 2023 SlideSlide2828 Copyright Box Hill Institute

UML Class DiagramUML Class Diagram

Person Class Name

Attributes (fields)

methods

+name : String

-dateOfBirth : String

-id : integer

+Person (String aName, String aDate, int aID)

April 19, 2023April 19, 2023 SlideSlide2929 Copyright Box Hill Institute

ReferencesReferences http://www.bhtafe.edu.au/bhive

http://www.byteofpython.info

http://www.ibiblio.org/g2swap/byteofpython/read/index.html

Farrell Joyce, 2006, An Object-Oriented Approach to Programming Logic and Design, [Thomson]

Sinan Si Alhir, Learning UML, [O’Reilly Press] Paul Harmon & Mark Watson, Understanding UML