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)

PPTX
Java
nirbhayverma8
 
PPTX
Java
nirbhayverma8
 
PPTX
Java tutorial part 3
Mumbai Academisc
 
PPTX
Java tutorial part 3
Mumbai Academisc
 
PPTX
Presentation 4th
Connex
 
PPTX
Presentation 4th
Connex
 
PPTX
Presentation 3rd
Connex
 
PPTX
Presentation 3rd
Connex
 
PPTX
class as the basis.pptx
Epsiba1
 
PPTX
class as the basis.pptx
Epsiba1
 
PPT
Objective-C for iOS Application Development
Dhaval Kaneria
 
PPT
Objective-C for iOS Application Development
Dhaval Kaneria
 
PPTX
Lecture 5.pptx
AshutoshTrivedi30
 
PPTX
Lecture 5.pptx
AshutoshTrivedi30
 
PPTX
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
PPTX
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
PPTX
Introduction to Object Oriented Programming in Python.pptx
eduardocehenmu
 
PPTX
Introduction to Object Oriented Programming in Python.pptx
eduardocehenmu
 
PDF
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
PDF
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
Java tutorial part 3
Mumbai Academisc
 
Java tutorial part 3
Mumbai Academisc
 
Presentation 4th
Connex
 
Presentation 4th
Connex
 
Presentation 3rd
Connex
 
Presentation 3rd
Connex
 
class as the basis.pptx
Epsiba1
 
class as the basis.pptx
Epsiba1
 
Objective-C for iOS Application Development
Dhaval Kaneria
 
Objective-C for iOS Application Development
Dhaval Kaneria
 
Lecture 5.pptx
AshutoshTrivedi30
 
Lecture 5.pptx
AshutoshTrivedi30
 
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
Object Oriented Programming in Python.pptx
grpvasundhara1993
 
Introduction to Object Oriented Programming in Python.pptx
eduardocehenmu
 
Introduction to Object Oriented Programming in Python.pptx
eduardocehenmu
 
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 
JAVA Class Presentation.pdf Vsjsjsnheheh
AnushreeP4
 

More from afsheenfaiq2 (20)

PPTX
Number Guessing Game using Artiifcal intelligence
afsheenfaiq2
 
PPTX
Sentiment Analyzer using Artificial Intelligence
afsheenfaiq2
 
PPTX
Object oriented programming design and implementation
afsheenfaiq2
 
PPTX
Anime Display for Weekly Passion Hour Club
afsheenfaiq2
 
PPTX
Creating Python Variables using Replit software
afsheenfaiq2
 
PPT
Introduction to Declaring Functions in Python
afsheenfaiq2
 
PDF
Sample Exam Questions on Python for revision
afsheenfaiq2
 
PPTX
GR 12 IOT Week 2.pptx
afsheenfaiq2
 
PPTX
IOT Week 20.pptx
afsheenfaiq2
 
PPTX
Lesson 17 - Pen Shade and Stamp.pptx
afsheenfaiq2
 
PPTX
AP CS PD 1.3 Week 4.pptx
afsheenfaiq2
 
PPTX
2D Polygons using Pen tools- Week 21.pptx
afsheenfaiq2
 
PPTX
Chapter 11 Strings.pptx
afsheenfaiq2
 
PPTX
Lesson 10_Size Block.pptx
afsheenfaiq2
 
PPT
CH05.ppt
afsheenfaiq2
 
PPT
Chapter05.ppt
afsheenfaiq2
 
PPTX
Gr 12 - Buzzer Project on Sound Production (W10).pptx
afsheenfaiq2
 
PPT
Network Topologies
afsheenfaiq2
 
PPTX
IoT-Week1-Day1-Lecture.pptx
afsheenfaiq2
 
PPTX
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Number Guessing Game using Artiifcal intelligence
afsheenfaiq2
 
Sentiment Analyzer using Artificial Intelligence
afsheenfaiq2
 
Object oriented programming design and implementation
afsheenfaiq2
 
Anime Display for Weekly Passion Hour Club
afsheenfaiq2
 
Creating Python Variables using Replit software
afsheenfaiq2
 
Introduction to Declaring Functions in Python
afsheenfaiq2
 
Sample Exam Questions on Python for revision
afsheenfaiq2
 
GR 12 IOT Week 2.pptx
afsheenfaiq2
 
IOT Week 20.pptx
afsheenfaiq2
 
Lesson 17 - Pen Shade and Stamp.pptx
afsheenfaiq2
 
AP CS PD 1.3 Week 4.pptx
afsheenfaiq2
 
2D Polygons using Pen tools- Week 21.pptx
afsheenfaiq2
 
Chapter 11 Strings.pptx
afsheenfaiq2
 
Lesson 10_Size Block.pptx
afsheenfaiq2
 
CH05.ppt
afsheenfaiq2
 
Chapter05.ppt
afsheenfaiq2
 
Gr 12 - Buzzer Project on Sound Production (W10).pptx
afsheenfaiq2
 
Network Topologies
afsheenfaiq2
 
IoT-Week1-Day1-Lecture.pptx
afsheenfaiq2
 
IoT-Week1-Day1-Lab.pptx
afsheenfaiq2
 
Ad

Recently uploaded (20)

PPTX
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
PPTX
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
PDF
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
PDF
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
PPTX
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
PDF
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
PPTX
Practical Applications of AI in Local Government
OnBoard
 
PPTX
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
PDF
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
PDF
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
PDF
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
PDF
Why aren't you using FME Flow's CPU Time?
Safe Software
 
PDF
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
PDF
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
PDF
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
PDF
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
PDF
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
PDF
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
Enabling the Digital Artisan – keynote at ICOCI 2025
Alan Dix
 
01_Approach Cyber- DORA Incident Management.pptx
FinTech Belgium
 
''Taming Explosive Growth: Building Resilience in a Hyper-Scaled Financial Pl...
Fwdays
 
Java 25 and Beyond - A Roadmap of Innovations
Ana-Maria Mihalceanu
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
ICONIQ State of AI Report 2025 - The Builder's Playbook
Razin Mustafiz
 
Smarter Governance with AI: What Every Board Needs to Know
OnBoard
 
Understanding AI Optimization AIO, LLMO, and GEO
CoDigital
 
Practical Applications of AI in Local Government
OnBoard
 
Paycifi - Programmable Trust_Breakfast_PPTXT
FinTech Belgium
 
FME as an Orchestration Tool with Principles From Data Gravity
Safe Software
 
“A Re-imagination of Embedded Vision System Design,” a Presentation from Imag...
Edge AI and Vision Alliance
 
GDG Cloud Southlake #44: Eyal Bukchin: Tightening the Kubernetes Feedback Loo...
James Anderson
 
Why aren't you using FME Flow's CPU Time?
Safe Software
 
TrustArc Webinar - Navigating APAC Data Privacy Laws: Compliance & Challenges
TrustArc
 
Hello I'm "AI" Your New _________________
Dr. Tathagat Varma
 
Bitkom eIDAS Summit | European Business Wallet: Use Cases, Macroeconomics, an...
Carsten Stoecker
 
How to Visualize the ​Spatio-Temporal Data Using CesiumJS​
SANGHEE SHIN
 
Simplify Your FME Flow Setup: Fault-Tolerant Deployment Made Easy with Packer...
Safe Software
 
Enhancing Environmental Monitoring with Real-Time Data Integration: Leveragin...
Safe Software
 
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