SlideShare a Scribd company logo
CSIT121
Object-Oriented Design and
Programming
Dr. Fenghui Ren
School of Computing and Information Technology
University of Wollongong
1
Lecture 3 outline
• Python class and object
• Class implementation with Python
• Add attributes and methods
• Initialisation of objects
• Class vs instance variables
• Class vs instance vs static methods
• Public, protected and private variables and methods
• A case study
2
HelloWorld (OOD)
Let's analyze the simplest possible Python OO program that has
only one class and one method
Class definition
To define a class you need to:
1. Use the class keyword (spelled with all lowercase letters)
2. Specify its name. A class name is its identifier.
By convention, class names
- can include only letters, digits, and underscores. No spaces.
- begin with a capital letter. If several words are combined, each shall start with a capital letter too
- should be meaningful DpGh, Abc, R1,WelcomeToPython, StaffMember, StreamBuffer
3. The class definition line is followed by the class contents, indented. pass can
be
used for skipping the class body.
4. Python uses a four-space indentation to delimit the classes, rather than
brackets
class HelloWorld:
pass
Class body
Class declaration
Class definition
• Although our first class does nothing, we still can run the program.
1. Save the class definition in a file named HelloWorld.py
2. Implement and run the program in IDLE.
Adding arbitrary attributes
• Objects should contain data which are defined as the attribute
• We can set arbitrary attributes on an instantiated object using ‘.’ (dot
notation).
• Syntax: <object>.<attribute> = <value>
Adding object behaviors
• We have data, and it is time to add behaviors.
• We start with a method called ‘greet’ which prints “Hello object world”.
• ‘greet’ method does not require any parameters.
• We call the method through the dot notation: <object>.<method>
Adding behaviors
• In Python, a method is defined with the def keyword, followed by a space,
the name of the method, and a set of parentheses containing the
parameter list.
• Method definition is terminated with a colon (:)
• The method body starts from the next line and is indented.
Syntax:
<def><methodName><(parameter list):>
<four space indentation><method body>
‘self’
argument
• With the same class definition, we can create different objects.
Therefore, we need to know which object calls the methods (object
methods).
• Object methods shall contain an argument referring to the object
itself.
• Normally, this argument is named ‘self’. The ‘self’ argument is a
reference to the object that the method is being invoked on.
• Of course, you can also call it by another name, such as ‘this’ or ‘bob’.
But we never seen a real Python programmer use any other name for
this variable
• A normal function or a class method does not have this ‘self’
argument.
‘self’
argument
• In Python OOP, a method is a function attached to a class.
• The ‘self’ parameter is a specific instance of that class.
• If you call the method with two different instances (objects), you are
calling the same method twice but passing two different objects as
the ‘self’ parameter
• When we call <object>.<method>, we do not have to pass the ‘self’
argument into it. It is because Python automatically pass it, i.e.,
method(object)
• Alternatively, we can invoke the function by the class name, and
explicitly pass our object as the ‘self’ argument using
<class>.<method(object)>
‘self’ argument
More arguments
• A method can contain multiple arguments
• Use the dot notation to call the method with all argument values (still
no need to include the ‘self’ argument) inside the parentheses
Adding attributes in your class definition
What if we forget to call the reset() function?
Summary
• Python is an interpreted language. The interpreter only ‘knows’ the code has been
executed.
• The ‘self’ argument is a reference to the object self. We should use ‘self.’ notation to access
the object functions and attribute values.
• If we try to access an attribute without a value, we will receive an error. Therefore, we must
make sure the attribute has a value before we use it.
• The ’reset()’ and ‘move()’ methods in the previous example assign values to attributes
‘self.x’ and ‘self.y’, and one of them must be executed for both point objects before we
calculate the distance of the two point objects.
• However, how do users know that? Furthermore, how do we force users to call the
‘reset()’
method?
• The better way is to let the interpreter call ‘reset()’ automatically for every new object
created.
• In OOD, a constructor (i.e., the function with the class name) refers to a special method that
creates and initialises the object automatically when it is created
• The Python initialisation method is the same as any other method but with a special name,
init (the leading and trailing are double underscores)
Initialisation of objects with init
Explain your class
• It is important to write API documentation to summarize what each object and
method does
• The best way to do it is to write it right into your code through the docstrings
• Docstrings are simply Python strings enclosed with apostrophes (') or quotation
marks (") characters.
• If docstrings are quite long and span multiple lines (the style guide suggests that
the line length should not exceed 80 characters), it can be formatted as multi-line
strings, enclosed in matching triple apostrophe (''') or triple quote (""") characters.
• A docstring should clearly and concisely summarize the purpose of the class or
method it is describing.
• It should explain any parameters whose usage is not immediately obvious and is
also a good place to include short examples of how to use the API.
• Any caveats or problems an unsuspecting user of the API should be aware of
should also be noted.
Explain your class
Object (instance) vs class (static) variables
• Object variables are for data unique to
each object.
• Object variables are defined inside
methods with the prefix ‘self’
• Access via self.<InstanceVariable>
• Class variables are for data shared by all
objects of the same class.
• Class variables are defined outside
methods
• Access via cls.<ClassVariable> or
<ClassName>.<ClassVariable>
Instance (object) vs class (static) variables
• start_point_x and start_point_y are class variables
• Changing the class variable values with Object point1,
then we can see the class variable values are modified
with Object point2
• Object point1 changes the start point from (0, 0) to
(1, 1). However, Object point2 is not initialised by the
new start point (1,1). Can you guess why?
• Can we use Point.start_point_x and
Point_start_point_y in the init() method?
Instance (object) vs class (static) variables
• No, we can not. It is because the class variables are not
created yet when we call the init() method
• How to resolve this problem?
• We use a sentinel default value instead.
Sentinel Default Value
• Can you understand and explain how the code is
executed and what the results are?
• Try to ‘run’ the code in your mind and write
down all outputs.
Class method
• Problem: we still have to create a Point object first, and then we can
modify the class variable start_point_x and start_point_y.
• Question: can we modify the start point directly without creating a Point
object?
• Answer: yes, we can. We can define a ‘change_start_point()’ method as
a class method by marking this method with a ‘@classmethod’
decorator.
• Then we can call the method with the class name, i.e.,
<ClassName>.<ClassMethod>.
• Actually, you can also call the class method with an object of the class,
such as <objectName>.<ClassMethod>. They do the same job.
Class method vs object method
• The object method has access to the object via the
’self’ argument. When the method is called, Python
replaces the ’self’ argument with the real object
name.
• Calling class method doesn’t have access to the
object, but only to the class. Python automatically
passes the class name as the first argument to the
function when we call the class method.
• Summary: Python calls the object method by
passing the object name as the first argument, and
calls the class method by passing the class name as
the first argument
Static method
• Question: Java has the static method, does Python also have the
static method?
• Answer: Yes, Python also has the static method, but the
definition of
‘static’ in Python is very different from Java or other OOPs.
• Java’s static method is the same as Python’s class method
• Python’s static method is the same as Python’s normal method,
i.e.,
no object instance or class will be pasted as the first argument.
• Python’s static method can be defined by marking this method with a
‘@staticmethod’ decorator.
• You are allowed to call a static method via either
Static method
Python access control
Most OOP languages have a concept of access control.
• (+) public members are accessible from outside the class.
• (-) private members are accessible from inside the class only.
• (#) protected members are accessible from inside the class or sub-classes
However, Python does not follow this exactly.
• Python does not believe in enforcing laws that might someday get in your way.
• Technically, all class members (attributes and methods) are publicly available, i.e., they can be
accessed directly from external.
• In Python, prefixes are used to only interpret the access control of members.
• _ (single underscore) prefixed to a member makes it protected but still can be accessed directly.
• (double underscore) prefixed to a member makes it private. It gives a strong suggestion not to
touch it from outside the class. Any attempt to do so will result in an AttributeError.
• However, Python performs name mangling of private variables. Every private member with a
double underscore can be accessed by adding the prefix ‘_<ClassName>’. So, private members can
still be accessed from outside the class, but the practice should be refrained.
Python access control
Python execution control
• A program written in C or Java needs the main() function to indicate the
starting point of execution.
• Python does not need the main() function as it is an interpreter-based
language.
• The execution of the Python program file starts from the first
statement.
• Python uses a special variable called ‘ name ’ (string) to
maintain the
scope of the code being executed.
• The top-level scope (top-level code executes here) is referred by the
value
‘ main ’
• You can check the scope in Python shell by typing ‘ name ’ in
IDEL.
Python execution control
• When you execute functions and
modules in the interpreter
shell directly,
they will be executed in the top-
level scope ‘ main ’
• We can also save a Python
program as a Python file, which
may contain multiple functions
and statements, such as
Python execution control
• We can use the command prompt/terminal to execute the Python file as a script. Then
the scope is ‘ main ’.
• We can also use the Python file as a module in another file or in interactive shell by
importing it. Then the scope is the module’s name, but not the ‘ main ’.
Python execution control
• The import statement starts
executing from the first statement
till the last statement.
• What if we just want to use the
‘add()’ method but not print the
details?
• We can use the special variable
‘ name ’ to check the scope
and execute the other statements
only when it executes from the
command prompt/terminal with
the scope of ‘ main ’ but not
when importing.
Python execution control
• However, when we execute it
from the command
prompt/terminal, it still executes
all statements because of it
being executed in the top-level
scope
‘ main ’.
• Thus, value of the ‘ name ’
allows the Python interpreter to
determine whether a module is
intended to be an executable
script.
A case study
Design and implement a Python program with OOD & OOP to calculate the
length of a given line segment.
Step 1: OOA
• To calculate the length of a given line segment, a LineSegment class can be
defined. The LineSegment class should contain two points, i.e., the starting
point and the ending point. The length of a line segment is the Cartesian
distance between the two points. So we also need to define a Point class.
• So the LineSegment class should have two points (attribute) and can
calculate the Cartesian distance of two points (behavior)
• To represent a point, a Point class should contain the coordinate (x, y) as its
attributes.
A case study
Design and implement a Python program with OOD & OOP to calculate the
length of a given line segment.
Step 2: OOD (UML)
𝑑𝑖𝑠𝑡𝑎𝑛𝑐𝑒 = (𝑥1 − 𝑥2)2+(𝑦1
− 𝑦2)2
A case study
Design and implement a Python program with
OOD & OOP to calculate the length of a given
line segment.
Step 3: OOP (Python): complete the Python
class code and test code. Remember, you should
create the ‘ init ’ method for every class.
Step 4 Execution Control: use the ‘ name ’
variable to ensure your testing code is only
executed in the command prompt/terminal.
A further question: can you modify this design
and code to calculate the total length of
consecutive line segments, such as
(0,0)->(3,4)->(5,7)->(2,8)?
Consecutive Line Segments
Which design is better?
Option 1:
Option 2:
Python 3 Object-Oriented
Programming
• Preface
• Chapter 2: Objects in Python
Python
• https://www.python.org/
Suggested reading

More Related Content

Similar to object oriented porgramming using Java programming (20)

Lecture 01 - Basic Concept About OOP With Python
Lecture 01 - Basic Concept About OOP With PythonLecture 01 - Basic Concept About OOP With Python
Lecture 01 - Basic Concept About OOP With Python
National College of Business Administration & Economics ( NCBA&E)
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.pptLecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.pptLecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
Kongunadu College of Engineering and Technology
 
مقدمة بايثون .pptx
مقدمة بايثون .pptxمقدمة بايثون .pptx
مقدمة بايثون .pptx
AlmutasemBillahAlwas
 
Unit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptxUnit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
Raghunath A
 
Introduction to OOP in Python
Introduction to OOP in PythonIntroduction to OOP in Python
Introduction to OOP in Python
Aleksander Fabijan
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
IPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptxIPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptx
DhavalaShreeBJain
 
introductiontooopinpython-171115114144.pdf
introductiontooopinpython-171115114144.pdfintroductiontooopinpython-171115114144.pdf
introductiontooopinpython-171115114144.pdf
AhmedSalama337512
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Python-Classes.pptx
Python-Classes.pptxPython-Classes.pptx
Python-Classes.pptx
Karudaiyar Ganapathy
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
oopinpyhtonnew-140722060241-phpapp01.pptx
oopinpyhtonnew-140722060241-phpapp01.pptxoopinpyhtonnew-140722060241-phpapp01.pptx
oopinpyhtonnew-140722060241-phpapp01.pptx
smartashammari
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
Santosh Verma
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHONUNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
Lecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.pptLecture topic - Python class lecture.ppt
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.pptLecture on Python class -lecture123456.ppt
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
Unit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptxUnit – V Object Oriented Programming in Python.pptx
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
Raghunath A
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Mohammad Reza Kamalifard
 
IPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptxIPP-M5-C1-Classes _ Objects python -S2.pptx
IPP-M5-C1-Classes _ Objects python -S2.pptx
DhavalaShreeBJain
 
introductiontooopinpython-171115114144.pdf
introductiontooopinpython-171115114144.pdfintroductiontooopinpython-171115114144.pdf
introductiontooopinpython-171115114144.pdf
AhmedSalama337512
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
oopinpyhtonnew-140722060241-phpapp01.pptx
oopinpyhtonnew-140722060241-phpapp01.pptxoopinpyhtonnew-140722060241-phpapp01.pptx
oopinpyhtonnew-140722060241-phpapp01.pptx
smartashammari
 

More from afsheenfaiq2 (19)

Object oriented programming design and implementation
Object oriented programming design and implementationObject oriented programming design and implementation
Object oriented programming design and implementation
afsheenfaiq2
 
Anime Display for Weekly Passion Hour Club
Anime Display for Weekly Passion Hour ClubAnime Display for Weekly Passion Hour Club
Anime Display for Weekly Passion Hour Club
afsheenfaiq2
 
Creating Python Variables using Replit software
Creating Python Variables using Replit softwareCreating Python Variables using Replit software
Creating Python Variables using Replit software
afsheenfaiq2
 
Introduction to Declaring Functions in Python
Introduction to Declaring Functions in PythonIntroduction to Declaring Functions in Python
Introduction to Declaring Functions in Python
afsheenfaiq2
 
Sample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionSample Exam Questions on Python for revision
Sample Exam Questions on Python for revision
afsheenfaiq2
 
GR 12 IOT Week 2.pptx
GR 12 IOT Week 2.pptxGR 12 IOT Week 2.pptx
GR 12 IOT Week 2.pptx
afsheenfaiq2
 
IOT Week 20.pptx
IOT Week 20.pptxIOT Week 20.pptx
IOT Week 20.pptx
afsheenfaiq2
 
Lesson 17 - Pen Shade and Stamp.pptx
Lesson 17 - Pen Shade and Stamp.pptxLesson 17 - Pen Shade and Stamp.pptx
Lesson 17 - Pen Shade and Stamp.pptx
afsheenfaiq2
 
AP CS PD 1.3 Week 4.pptx
AP CS PD 1.3 Week 4.pptxAP CS PD 1.3 Week 4.pptx
AP CS PD 1.3 Week 4.pptx
afsheenfaiq2
 
2D Polygons using Pen tools- Week 21.pptx
2D Polygons using Pen tools- Week 21.pptx2D Polygons using Pen tools- Week 21.pptx
2D Polygons using Pen tools- Week 21.pptx
afsheenfaiq2
 
Chapter 11 Strings.pptx
Chapter 11 Strings.pptxChapter 11 Strings.pptx
Chapter 11 Strings.pptx
afsheenfaiq2
 
Lesson 10_Size Block.pptx
Lesson 10_Size Block.pptxLesson 10_Size Block.pptx
Lesson 10_Size Block.pptx
afsheenfaiq2
 
CH05.ppt
CH05.pptCH05.ppt
CH05.ppt
afsheenfaiq2
 
Chapter05.ppt
Chapter05.pptChapter05.ppt
Chapter05.ppt
afsheenfaiq2
 
Gr 12 - Buzzer Project on Sound Production (W10).pptx
Gr 12 - Buzzer Project on Sound Production (W10).pptxGr 12 - Buzzer Project on Sound Production (W10).pptx
Gr 12 - Buzzer Project on Sound Production (W10).pptx
afsheenfaiq2
 
Network Topologies
Network TopologiesNetwork Topologies
Network Topologies
afsheenfaiq2
 
IoT-Week1-Day1-Lecture.pptx
IoT-Week1-Day1-Lecture.pptxIoT-Week1-Day1-Lecture.pptx
IoT-Week1-Day1-Lecture.pptx
afsheenfaiq2
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Lecture 1.pptx
Lecture 1.pptxLecture 1.pptx
Lecture 1.pptx
afsheenfaiq2
 
Object oriented programming design and implementation
Object oriented programming design and implementationObject oriented programming design and implementation
Object oriented programming design and implementation
afsheenfaiq2
 
Anime Display for Weekly Passion Hour Club
Anime Display for Weekly Passion Hour ClubAnime Display for Weekly Passion Hour Club
Anime Display for Weekly Passion Hour Club
afsheenfaiq2
 
Creating Python Variables using Replit software
Creating Python Variables using Replit softwareCreating Python Variables using Replit software
Creating Python Variables using Replit software
afsheenfaiq2
 
Introduction to Declaring Functions in Python
Introduction to Declaring Functions in PythonIntroduction to Declaring Functions in Python
Introduction to Declaring Functions in Python
afsheenfaiq2
 
Sample Exam Questions on Python for revision
Sample Exam Questions on Python for revisionSample Exam Questions on Python for revision
Sample Exam Questions on Python for revision
afsheenfaiq2
 
GR 12 IOT Week 2.pptx
GR 12 IOT Week 2.pptxGR 12 IOT Week 2.pptx
GR 12 IOT Week 2.pptx
afsheenfaiq2
 
Lesson 17 - Pen Shade and Stamp.pptx
Lesson 17 - Pen Shade and Stamp.pptxLesson 17 - Pen Shade and Stamp.pptx
Lesson 17 - Pen Shade and Stamp.pptx
afsheenfaiq2
 
AP CS PD 1.3 Week 4.pptx
AP CS PD 1.3 Week 4.pptxAP CS PD 1.3 Week 4.pptx
AP CS PD 1.3 Week 4.pptx
afsheenfaiq2
 
2D Polygons using Pen tools- Week 21.pptx
2D Polygons using Pen tools- Week 21.pptx2D Polygons using Pen tools- Week 21.pptx
2D Polygons using Pen tools- Week 21.pptx
afsheenfaiq2
 
Chapter 11 Strings.pptx
Chapter 11 Strings.pptxChapter 11 Strings.pptx
Chapter 11 Strings.pptx
afsheenfaiq2
 
Lesson 10_Size Block.pptx
Lesson 10_Size Block.pptxLesson 10_Size Block.pptx
Lesson 10_Size Block.pptx
afsheenfaiq2
 
Gr 12 - Buzzer Project on Sound Production (W10).pptx
Gr 12 - Buzzer Project on Sound Production (W10).pptxGr 12 - Buzzer Project on Sound Production (W10).pptx
Gr 12 - Buzzer Project on Sound Production (W10).pptx
afsheenfaiq2
 
Network Topologies
Network TopologiesNetwork Topologies
Network Topologies
afsheenfaiq2
 
IoT-Week1-Day1-Lecture.pptx
IoT-Week1-Day1-Lecture.pptxIoT-Week1-Day1-Lecture.pptx
IoT-Week1-Day1-Lecture.pptx
afsheenfaiq2
 
IoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptxIoT-Week1-Day1-Lab.pptx
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Ad

Recently uploaded (20)

Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Soulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate reviewSoulmaite review - Find Real AI soulmate review
Soulmaite review - Find Real AI soulmate review
Soulmaite
 
7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf7 Salesforce Data Cloud Best Practices.pdf
7 Salesforce Data Cloud Best Practices.pdf
Minuscule Technologies
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
Dancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptxDancing with AI - A Developer's Journey.pptx
Dancing with AI - A Developer's Journey.pptx
Elliott Richmond
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to KnowWhat is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
What is Oracle EPM A Guide to Oracle EPM Cloud Everything You Need to Know
SMACT Works
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0FCF- Getting Started in Cybersecurity 3.0
FCF- Getting Started in Cybersecurity 3.0
RodrigoMori7
 
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyesEnd-to-end Assurance for SD-WAN & SASE with ThousandEyes
End-to-end Assurance for SD-WAN & SASE with ThousandEyes
ThousandEyes
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025Azure vs AWS  Which Cloud Platform Is Best for Your Business in 2025
Azure vs AWS Which Cloud Platform Is Best for Your Business in 2025
Infrassist Technologies Pvt. Ltd.
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
DevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical PodcastDevOps in the Modern Era - Thoughtfully Critical Podcast
DevOps in the Modern Era - Thoughtfully Critical Podcast
Chris Wahl
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Ad

object oriented porgramming using Java programming

  • 1. CSIT121 Object-Oriented Design and Programming Dr. Fenghui Ren School of Computing and Information Technology University of Wollongong 1
  • 2. Lecture 3 outline • Python class and object • Class implementation with Python • Add attributes and methods • Initialisation of objects • Class vs instance variables • Class vs instance vs static methods • Public, protected and private variables and methods • A case study 2
  • 3. HelloWorld (OOD) Let's analyze the simplest possible Python OO program that has only one class and one method
  • 4. Class definition To define a class you need to: 1. Use the class keyword (spelled with all lowercase letters) 2. Specify its name. A class name is its identifier. By convention, class names - can include only letters, digits, and underscores. No spaces. - begin with a capital letter. If several words are combined, each shall start with a capital letter too - should be meaningful DpGh, Abc, R1,WelcomeToPython, StaffMember, StreamBuffer 3. The class definition line is followed by the class contents, indented. pass can be used for skipping the class body. 4. Python uses a four-space indentation to delimit the classes, rather than brackets class HelloWorld: pass Class body Class declaration
  • 5. Class definition • Although our first class does nothing, we still can run the program. 1. Save the class definition in a file named HelloWorld.py 2. Implement and run the program in IDLE.
  • 6. Adding arbitrary attributes • Objects should contain data which are defined as the attribute • We can set arbitrary attributes on an instantiated object using ‘.’ (dot notation). • Syntax: <object>.<attribute> = <value>
  • 7. Adding object behaviors • We have data, and it is time to add behaviors. • We start with a method called ‘greet’ which prints “Hello object world”. • ‘greet’ method does not require any parameters. • We call the method through the dot notation: <object>.<method>
  • 8. Adding behaviors • In Python, a method is defined with the def keyword, followed by a space, the name of the method, and a set of parentheses containing the parameter list. • Method definition is terminated with a colon (:) • The method body starts from the next line and is indented. Syntax: <def><methodName><(parameter list):> <four space indentation><method body>
  • 9. ‘self’ argument • With the same class definition, we can create different objects. Therefore, we need to know which object calls the methods (object methods). • Object methods shall contain an argument referring to the object itself. • Normally, this argument is named ‘self’. The ‘self’ argument is a reference to the object that the method is being invoked on. • Of course, you can also call it by another name, such as ‘this’ or ‘bob’. But we never seen a real Python programmer use any other name for this variable • A normal function or a class method does not have this ‘self’ argument.
  • 10. ‘self’ argument • In Python OOP, a method is a function attached to a class. • The ‘self’ parameter is a specific instance of that class. • If you call the method with two different instances (objects), you are calling the same method twice but passing two different objects as the ‘self’ parameter • When we call <object>.<method>, we do not have to pass the ‘self’ argument into it. It is because Python automatically pass it, i.e., method(object) • Alternatively, we can invoke the function by the class name, and explicitly pass our object as the ‘self’ argument using <class>.<method(object)>
  • 12. More arguments • A method can contain multiple arguments • Use the dot notation to call the method with all argument values (still no need to include the ‘self’ argument) inside the parentheses
  • 13. Adding attributes in your class definition What if we forget to call the reset() function?
  • 14. Summary • Python is an interpreted language. The interpreter only ‘knows’ the code has been executed. • The ‘self’ argument is a reference to the object self. We should use ‘self.’ notation to access the object functions and attribute values. • If we try to access an attribute without a value, we will receive an error. Therefore, we must make sure the attribute has a value before we use it. • The ’reset()’ and ‘move()’ methods in the previous example assign values to attributes ‘self.x’ and ‘self.y’, and one of them must be executed for both point objects before we calculate the distance of the two point objects. • However, how do users know that? Furthermore, how do we force users to call the ‘reset()’ method? • The better way is to let the interpreter call ‘reset()’ automatically for every new object created. • In OOD, a constructor (i.e., the function with the class name) refers to a special method that creates and initialises the object automatically when it is created • The Python initialisation method is the same as any other method but with a special name, init (the leading and trailing are double underscores)
  • 16. Explain your class • It is important to write API documentation to summarize what each object and method does • The best way to do it is to write it right into your code through the docstrings • Docstrings are simply Python strings enclosed with apostrophes (') or quotation marks (") characters. • If docstrings are quite long and span multiple lines (the style guide suggests that the line length should not exceed 80 characters), it can be formatted as multi-line strings, enclosed in matching triple apostrophe (''') or triple quote (""") characters. • A docstring should clearly and concisely summarize the purpose of the class or method it is describing. • It should explain any parameters whose usage is not immediately obvious and is also a good place to include short examples of how to use the API. • Any caveats or problems an unsuspecting user of the API should be aware of should also be noted.
  • 18. Object (instance) vs class (static) variables • Object variables are for data unique to each object. • Object variables are defined inside methods with the prefix ‘self’ • Access via self.<InstanceVariable> • Class variables are for data shared by all objects of the same class. • Class variables are defined outside methods • Access via cls.<ClassVariable> or <ClassName>.<ClassVariable>
  • 19. Instance (object) vs class (static) variables • start_point_x and start_point_y are class variables • Changing the class variable values with Object point1, then we can see the class variable values are modified with Object point2 • Object point1 changes the start point from (0, 0) to (1, 1). However, Object point2 is not initialised by the new start point (1,1). Can you guess why? • Can we use Point.start_point_x and Point_start_point_y in the init() method?
  • 20. Instance (object) vs class (static) variables • No, we can not. It is because the class variables are not created yet when we call the init() method • How to resolve this problem? • We use a sentinel default value instead.
  • 21. Sentinel Default Value • Can you understand and explain how the code is executed and what the results are? • Try to ‘run’ the code in your mind and write down all outputs.
  • 22. Class method • Problem: we still have to create a Point object first, and then we can modify the class variable start_point_x and start_point_y. • Question: can we modify the start point directly without creating a Point object? • Answer: yes, we can. We can define a ‘change_start_point()’ method as a class method by marking this method with a ‘@classmethod’ decorator. • Then we can call the method with the class name, i.e., <ClassName>.<ClassMethod>. • Actually, you can also call the class method with an object of the class, such as <objectName>.<ClassMethod>. They do the same job.
  • 23. Class method vs object method • The object method has access to the object via the ’self’ argument. When the method is called, Python replaces the ’self’ argument with the real object name. • Calling class method doesn’t have access to the object, but only to the class. Python automatically passes the class name as the first argument to the function when we call the class method. • Summary: Python calls the object method by passing the object name as the first argument, and calls the class method by passing the class name as the first argument
  • 24. Static method • Question: Java has the static method, does Python also have the static method? • Answer: Yes, Python also has the static method, but the definition of ‘static’ in Python is very different from Java or other OOPs. • Java’s static method is the same as Python’s class method • Python’s static method is the same as Python’s normal method, i.e., no object instance or class will be pasted as the first argument. • Python’s static method can be defined by marking this method with a ‘@staticmethod’ decorator. • You are allowed to call a static method via either
  • 26. Python access control Most OOP languages have a concept of access control. • (+) public members are accessible from outside the class. • (-) private members are accessible from inside the class only. • (#) protected members are accessible from inside the class or sub-classes However, Python does not follow this exactly. • Python does not believe in enforcing laws that might someday get in your way. • Technically, all class members (attributes and methods) are publicly available, i.e., they can be accessed directly from external. • In Python, prefixes are used to only interpret the access control of members. • _ (single underscore) prefixed to a member makes it protected but still can be accessed directly. • (double underscore) prefixed to a member makes it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError. • However, Python performs name mangling of private variables. Every private member with a double underscore can be accessed by adding the prefix ‘_<ClassName>’. So, private members can still be accessed from outside the class, but the practice should be refrained.
  • 28. Python execution control • A program written in C or Java needs the main() function to indicate the starting point of execution. • Python does not need the main() function as it is an interpreter-based language. • The execution of the Python program file starts from the first statement. • Python uses a special variable called ‘ name ’ (string) to maintain the scope of the code being executed. • The top-level scope (top-level code executes here) is referred by the value ‘ main ’ • You can check the scope in Python shell by typing ‘ name ’ in IDEL.
  • 29. Python execution control • When you execute functions and modules in the interpreter shell directly, they will be executed in the top- level scope ‘ main ’ • We can also save a Python program as a Python file, which may contain multiple functions and statements, such as
  • 30. Python execution control • We can use the command prompt/terminal to execute the Python file as a script. Then the scope is ‘ main ’. • We can also use the Python file as a module in another file or in interactive shell by importing it. Then the scope is the module’s name, but not the ‘ main ’.
  • 31. Python execution control • The import statement starts executing from the first statement till the last statement. • What if we just want to use the ‘add()’ method but not print the details? • We can use the special variable ‘ name ’ to check the scope and execute the other statements only when it executes from the command prompt/terminal with the scope of ‘ main ’ but not when importing.
  • 32. Python execution control • However, when we execute it from the command prompt/terminal, it still executes all statements because of it being executed in the top-level scope ‘ main ’. • Thus, value of the ‘ name ’ allows the Python interpreter to determine whether a module is intended to be an executable script.
  • 33. A case study Design and implement a Python program with OOD & OOP to calculate the length of a given line segment. Step 1: OOA • To calculate the length of a given line segment, a LineSegment class can be defined. The LineSegment class should contain two points, i.e., the starting point and the ending point. The length of a line segment is the Cartesian distance between the two points. So we also need to define a Point class. • So the LineSegment class should have two points (attribute) and can calculate the Cartesian distance of two points (behavior) • To represent a point, a Point class should contain the coordinate (x, y) as its attributes.
  • 34. A case study Design and implement a Python program with OOD & OOP to calculate the length of a given line segment. Step 2: OOD (UML) 𝑑𝑖𝑠𝑡𝑎𝑛𝑐𝑒 = (𝑥1 − 𝑥2)2+(𝑦1 − 𝑦2)2
  • 35. A case study Design and implement a Python program with OOD & OOP to calculate the length of a given line segment. Step 3: OOP (Python): complete the Python class code and test code. Remember, you should create the ‘ init ’ method for every class. Step 4 Execution Control: use the ‘ name ’ variable to ensure your testing code is only executed in the command prompt/terminal. A further question: can you modify this design and code to calculate the total length of consecutive line segments, such as (0,0)->(3,4)->(5,7)->(2,8)?
  • 36. Consecutive Line Segments Which design is better? Option 1: Option 2:
  • 37. Python 3 Object-Oriented Programming • Preface • Chapter 2: Objects in Python Python • https://www.python.org/ Suggested reading