SlideShare a Scribd company logo
1 of 16
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

Similar to 08-classes-objects.ppt (20)

Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
обзор Python
обзор Pythonобзор Python
обзор Python
 
C#2
C#2C#2
C#2
 
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Node.js extensions in C++
Node.js extensions in C++Node.js extensions in C++
Node.js extensions in C++
 
L03 Software Design
L03 Software DesignL03 Software Design
L03 Software Design
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Lecture2.pdf
Lecture2.pdfLecture2.pdf
Lecture2.pdf
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
2java Oop
2java Oop2java Oop
2java Oop
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Declarative Data Modeling in Python
Declarative Data Modeling in PythonDeclarative Data Modeling in Python
Declarative Data Modeling in Python
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Unit ii
Unit iiUnit ii
Unit ii
 
Pythonclass
PythonclassPythonclass
Pythonclass
 

Recently uploaded

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 

Recently uploaded (20)

ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 

08-classes-objects.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

  1. 2
  2. 3
  3. 5
  4. 6
  5. 9
  6. 14
  7. 15
  8. 16