SlideShare a Scribd company logo
Unit 8
Classes and Objects; Inheritance
Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.
Except where otherwise noted, this work is licensed under:
http://creativecommons.org/licenses/by-nc-sa/3.0
2
OOP, Defining a Class
• Python was built as a procedural language
– OOP exists and works fine, but feels a bit more "tacked on"
– Java probably does classes better than Python (gasp)
• Declaring a class:
class name:
statements
3
Fields
name = value
– Example:
class Point:
x = 0
y = 0
# main
p1 = Point()
p1.x = 2
p1.y = -5
– can be declared directly inside class (as shown here)
or in constructors (more common)
– Python does not really have encapsulation or private fields
• relies on caller to "be nice" and not mess with objects' contents
point.py
1
2
3
class Point:
x = 0
y = 0
4
Using a Class
import class
– client programs must import the classes they use
point_main.py
1
2
3
4
5
6
7
8
9
10
from Point import *
# main
p1 = Point()
p1.x = 7
p1.y = -3
...
# Python objects are dynamic (can add fields any time!)
p1.name = "Tyler Durden"
5
Object Methods
def name(self, parameter, ..., parameter):
statements
– self must be the first parameter to any object method
• represents the "implicit parameter" (this in Java)
– must access the object's fields through the self reference
class Point:
def translate(self, dx, dy):
self.x += dx
self.y += dy
...
6
"Implicit" Parameter (self)
• Java: this, implicit
public void translate(int dx, int dy) {
x += dx; // this.x += dx;
y += dy; // this.y += dy;
}
• Python: self, explicit
def translate(self, dx, dy):
self.x += dx
self.y += dy
– Exercise: Write distance, set_location, and
distance_from_origin methods.
7
Exercise Answer
point.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from math import *
class Point:
x = 0
y = 0
def set_location(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y)
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return sqrt(dx * dx + dy * dy)
8
Calling Methods
• A client can call the methods of an object in two ways:
– (the value of self can be an implicit or explicit parameter)
1) object.method(parameters)
or
2) Class.method(object, parameters)
• Example:
p = Point(3, -4)
p.translate(1, 5)
Point.translate(p, 1, 5)
9
Constructors
def __init__(self, parameter, ..., parameter):
statements
– a constructor is a special method with the name __init__
– Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
...
• How would we make it possible to construct a
Point() with no parameters to get (0, 0)?
10
toString and __str__
def __str__(self):
return string
– equivalent to Java's toString (converts object to a string)
– invoked automatically when str or print is called
Exercise: Write a __str__ method for Point objects that
returns strings like "(3, -14)"
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
11
Complete Point Class
point.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from math import *
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance_from_origin(self):
return sqrt(self.x * self.x + self.y * self.y)
def distance(self, other):
dx = self.x - other.x
dy = self.y - other.y
return sqrt(dx * dx + dy * dy)
def translate(self, dx, dy):
self.x += dx
self.y += dy
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"
12
Operator Overloading
• operator overloading: You can define functions so that
Python's built-in operators can be used with your class.
• See also: http://docs.python.org/ref/customization.html
Operator Class Method
- __neg__(self, other)
+ __pos__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
Unary Operators
- __neg__(self)
+ __pos__(self)
Operator Class Method
== __eq__(self, other)
!= __ne__(self, other)
< __lt__(self, other)
> __gt__(self, other)
<= __le__(self, other)
>= __ge__(self, other)
13
Exercise
• Exercise: Write a Fraction class to represent rational
numbers like 1/2 and -3/8.
• Fractions should always be stored in reduced form; for
example, store 4/12 as 1/3 and 6/-9 as -2/3.
– Hint: A GCD (greatest common divisor) function may help.
• Define add and multiply methods that accept another
Fraction as a parameter and modify the existing
Fraction by adding/multiplying it by that parameter.
• Define +, *, ==, and < operators.
14
Generating Exceptions
raise ExceptionType("message")
– useful when the client uses your object improperly
– types: ArithmeticError, AssertionError, IndexError,
NameError, SyntaxError, TypeError, ValueError
– Example:
class BankAccount:
...
def deposit(self, amount):
if amount < 0:
raise ValueError("negative amount")
...
15
Inheritance
class name(superclass):
statements
– Example:
class Point3D(Point): # Point3D extends Point
z = 0
...
• Python also supports multiple inheritance
class name(superclass, ..., superclass):
statements
(if > 1 superclass has the same field/method, conflicts are resolved in left-to-right order)
16
Calling Superclass Methods
• methods: class.method(object, parameters)
• constructors: class.__init__(parameters)
class Point3D(Point):
z = 0
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z
def translate(self, dx, dy, dz):
Point.translate(self, dx, dy)
self.z += dz

More Related Content

PPTX
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
PDF
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
ID Bilişim ve Ticaret Ltd. Şti.
 
PPTX
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
PPTX
Object Oriented Programming.pptx
SAICHARANREDDYN
 
PPTX
Class, object and inheritance in python
Santosh Verma
 
PPTX
Creating Objects in Python
Damian T. Gordon
 
PPT
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
PPT
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
ID Bilişim ve Ticaret Ltd. Şti.
 
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Class, object and inheritance in python
Santosh Verma
 
Creating Objects in Python
Damian T. Gordon
 
Lecture topic - Python class lecture.ppt
Reji K Dhaman
 
Lecture on Python class -lecture123456.ppt
Reji K Dhaman
 

Similar to OOC in python.ppt (20)

PPTX
VTU Python Module 5 , Class and Objects and Debugging
rickyghoshiit
 
PPTX
Module 4.pptx
charancherry185493
 
PPTX
object oriented porgramming using Java programming
afsheenfaiq2
 
PPTX
Python – Object Oriented Programming
Raghunath A
 
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
PDF
Module IV_updated(old).pdf
R.K.College of engg & Tech
 
PPT
07slide.ppt
NuurAxmed2
 
PPTX
Python OOPs
Binay Kumar Ray
 
PDF
Lecture1
Ritu Chaturvedi
 
PDF
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
horiamommand
 
PPT
Python3
Ruchika Sinha
 
PPTX
Python advance
Mukul Kirti Verma
 
PDF
Python unit 3 m.sc cs
KALAISELVI P
 
PPTX
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
thuy27042005thieu
 
PPTX
Python: Migrating from Procedural to Object-Oriented Programming
Damian T. Gordon
 
PPTX
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
PPTX
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
PPTX
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
VTU Python Module 5 , Class and Objects and Debugging
rickyghoshiit
 
Module 4.pptx
charancherry185493
 
object oriented porgramming using Java programming
afsheenfaiq2
 
Python – Object Oriented Programming
Raghunath A
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Module IV_updated(old).pdf
R.K.College of engg & Tech
 
07slide.ppt
NuurAxmed2
 
Python OOPs
Binay Kumar Ray
 
Lecture1
Ritu Chaturvedi
 
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
horiamommand
 
Python3
Ruchika Sinha
 
Python advance
Mukul Kirti Verma
 
Python unit 3 m.sc cs
KALAISELVI P
 
2_Classes.pptxjdhfhdfohfshfklsfskkfsdklsdk
thuy27042005thieu
 
Python: Migrating from Procedural to Object-Oriented Programming
Damian T. Gordon
 
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
OOPS-PYTHON.pptx OOPS IN PYTHON APPLIED PROGRAMMING
NagarathnaRajur2
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
Ad

Recently uploaded (20)

PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
 
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
 
Software Development Company | KodekX
KodekX
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Google’s NotebookLM Unveils Video Overviews
SOFTTECHHUB
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Why Your AI & Cybersecurity Hiring Still Misses the Mark in 2025
Virtual Employee Pvt. Ltd.
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
Ad

OOC in python.ppt

  • 1. Unit 8 Classes and Objects; Inheritance Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0
  • 2. 2 OOP, Defining a Class • Python was built as a procedural language – OOP exists and works fine, but feels a bit more "tacked on" – Java probably does classes better than Python (gasp) • Declaring a class: class name: statements
  • 3. 3 Fields name = value – Example: class Point: x = 0 y = 0 # main p1 = Point() p1.x = 2 p1.y = -5 – can be declared directly inside class (as shown here) or in constructors (more common) – Python does not really have encapsulation or private fields • relies on caller to "be nice" and not mess with objects' contents point.py 1 2 3 class Point: x = 0 y = 0
  • 4. 4 Using a Class import class – client programs must import the classes they use point_main.py 1 2 3 4 5 6 7 8 9 10 from Point import * # main p1 = Point() p1.x = 7 p1.y = -3 ... # Python objects are dynamic (can add fields any time!) p1.name = "Tyler Durden"
  • 5. 5 Object Methods def name(self, parameter, ..., parameter): statements – self must be the first parameter to any object method • represents the "implicit parameter" (this in Java) – must access the object's fields through the self reference class Point: def translate(self, dx, dy): self.x += dx self.y += dy ...
  • 6. 6 "Implicit" Parameter (self) • Java: this, implicit public void translate(int dx, int dy) { x += dx; // this.x += dx; y += dy; // this.y += dy; } • Python: self, explicit def translate(self, dx, dy): self.x += dx self.y += dy – Exercise: Write distance, set_location, and distance_from_origin methods.
  • 7. 7 Exercise Answer point.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 from math import * class Point: x = 0 y = 0 def set_location(self, x, y): self.x = x self.y = y def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y) def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy)
  • 8. 8 Calling Methods • A client can call the methods of an object in two ways: – (the value of self can be an implicit or explicit parameter) 1) object.method(parameters) or 2) Class.method(object, parameters) • Example: p = Point(3, -4) p.translate(1, 5) Point.translate(p, 1, 5)
  • 9. 9 Constructors def __init__(self, parameter, ..., parameter): statements – a constructor is a special method with the name __init__ – Example: class Point: def __init__(self, x, y): self.x = x self.y = y ... • How would we make it possible to construct a Point() with no parameters to get (0, 0)?
  • 10. 10 toString and __str__ def __str__(self): return string – equivalent to Java's toString (converts object to a string) – invoked automatically when str or print is called Exercise: Write a __str__ method for Point objects that returns strings like "(3, -14)" def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"
  • 11. 11 Complete Point Class point.py 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 from math import * class Point: def __init__(self, x, y): self.x = x self.y = y def distance_from_origin(self): return sqrt(self.x * self.x + self.y * self.y) def distance(self, other): dx = self.x - other.x dy = self.y - other.y return sqrt(dx * dx + dy * dy) def translate(self, dx, dy): self.x += dx self.y += dy def __str__(self): return "(" + str(self.x) + ", " + str(self.y) + ")"
  • 12. 12 Operator Overloading • operator overloading: You can define functions so that Python's built-in operators can be used with your class. • See also: http://docs.python.org/ref/customization.html Operator Class Method - __neg__(self, other) + __pos__(self, other) * __mul__(self, other) / __truediv__(self, other) Unary Operators - __neg__(self) + __pos__(self) Operator Class Method == __eq__(self, other) != __ne__(self, other) < __lt__(self, other) > __gt__(self, other) <= __le__(self, other) >= __ge__(self, other)
  • 13. 13 Exercise • Exercise: Write a Fraction class to represent rational numbers like 1/2 and -3/8. • Fractions should always be stored in reduced form; for example, store 4/12 as 1/3 and 6/-9 as -2/3. – Hint: A GCD (greatest common divisor) function may help. • Define add and multiply methods that accept another Fraction as a parameter and modify the existing Fraction by adding/multiplying it by that parameter. • Define +, *, ==, and < operators.
  • 14. 14 Generating Exceptions raise ExceptionType("message") – useful when the client uses your object improperly – types: ArithmeticError, AssertionError, IndexError, NameError, SyntaxError, TypeError, ValueError – Example: class BankAccount: ... def deposit(self, amount): if amount < 0: raise ValueError("negative amount") ...
  • 15. 15 Inheritance class name(superclass): statements – Example: class Point3D(Point): # Point3D extends Point z = 0 ... • Python also supports multiple inheritance class name(superclass, ..., superclass): statements (if > 1 superclass has the same field/method, conflicts are resolved in left-to-right order)
  • 16. 16 Calling Superclass Methods • methods: class.method(object, parameters) • constructors: class.__init__(parameters) class Point3D(Point): z = 0 def __init__(self, x, y, z): Point.__init__(self, x, y) self.z = z def translate(self, dx, dy, dz): Point.translate(self, dx, dy) self.z += dz

Editor's Notes