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

Similar to OOC in python.ppt

Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 
обзор Python
обзор Pythonобзор Python
обзор Python
Yehor Nazarkin
 
C#2
C#2C#2
Python - OOP Programming
Python - OOP ProgrammingPython - OOP Programming
Python - OOP Programming
Andrew Ferlitsch
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
Jim Roepcke
 
Node.js extensions in C++
Node.js extensions in C++Node.js extensions in C++
Node.js extensions in C++
Kenneth Geisshirt
 
L03 Software Design
L03 Software DesignL03 Software Design
L03 Software Design
Ólafur Andri Ragnarsson
 
Function overloading
Function overloadingFunction overloading
Function overloading
Swarup Kumar Boro
 
Lecture2.pdf
Lecture2.pdfLecture2.pdf
Lecture2.pdf
SakhilejasonMsibi
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
Kevlin Henney
 
2java Oop
2java Oop2java Oop
2java Oop
Adil Jafri
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
Creating Objects in Python
Creating Objects in PythonCreating Objects in Python
Creating Objects in Python
Damian T. Gordon
 
CPP Homework Help
CPP Homework HelpCPP Homework Help
CPP Homework Help
C++ Homework Help
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
Connex
 
Declarative Data Modeling in Python
Declarative Data Modeling in PythonDeclarative Data Modeling in Python
Declarative Data Modeling in Python
Joshua Forman
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Unit ii
Unit iiUnit ii
Unit ii
snehaarao19
 
Pythonclass
PythonclassPythonclass

Similar to OOC in python.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

Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
Pixlogix Infotech
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Alpen-Adria-Universität
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Safe Software
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
GDSC PJATK
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
Octavian Nadolu
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
flufftailshop
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
Pravash Chandra Das
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
Hiike
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
panagenda
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Wask
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
LucaBarbaro3
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
fredae14
 

Recently uploaded (20)

Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Best 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERPBest 20 SEO Techniques To Improve Website Visibility In SERP
Best 20 SEO Techniques To Improve Website Visibility In SERP
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing InstancesEnergy Efficient Video Encoding for Cloud and Edge Computing Instances
Energy Efficient Video Encoding for Cloud and Edge Computing Instances
 
Driving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success StoryDriving Business Innovation: Latest Generative AI Advancements & Success Story
Driving Business Innovation: Latest Generative AI Advancements & Success Story
 
Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!Finale of the Year: Apply for Next One!
Finale of the Year: Apply for Next One!
 
Artificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopmentArtificial Intelligence for XMLDevelopment
Artificial Intelligence for XMLDevelopment
 
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdfNunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
Nunit vs XUnit vs MSTest Differences Between These Unit Testing Frameworks.pdf
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 
Operating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptxOperating System Used by Users in day-to-day life.pptx
Operating System Used by Users in day-to-day life.pptx
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - HiikeSystem Design Case Study: Building a Scalable E-Commerce Platform - Hiike
System Design Case Study: Building a Scalable E-Commerce Platform - Hiike
 
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUHCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAU
 
Digital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying AheadDigital Marketing Trends in 2024 | Guide for Staying Ahead
Digital Marketing Trends in 2024 | Guide for Staying Ahead
 
Trusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process MiningTrusted Execution Environment for Decentralized Process Mining
Trusted Execution Environment for Decentralized Process Mining
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Recommendation System using RAG Architecture
Recommendation System using RAG ArchitectureRecommendation System using RAG Architecture
Recommendation System using RAG Architecture
 

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

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