SlideShare a Scribd company logo
Play with Python
            Lab2
Object Oriented Programming
About Lecture 2 and Lab 2
Lecture 2 and its lab aims at covering Basic
  Object Oriented Programming concepts
Classes, Constructor (__init__) and Objects
Example 1
Create a new Project in
                                  shp1 = IrregularShape()
  Aptana "Lab2", then             shp1.AddShape(Square(3))

  add a new PyDev                 shp1.AddShape(Triangle(4, 5))
                                  shp1.AddShape(Square(10))
  module called main              print shp1.Area()

Write the following code          ========
  in your main file:              Output:
                                  119.0
class Square:
         def __init__(self, l):
         self.length = l
         def Area(self):
         return self.length**2
class Triangle:
     def __init__(self, b, h):
Example 1
class Square:
     def __init__(self, l):
       self.length = l
     def Area(self):
        return self.length**2
class Triangle:
   def __init__(self, b, h):
      self.base = b
      self.height = h
   def Area(self):
      return 0.5*self.base*self.height
Example 1
class IrregularShape:
   def __init__(self):
      self.shapes = []
   def AddShape(self, shape):
   self.shapes.append(shape)
   def Area(self):
   area = 0
   for shape in self.shapes:
      area += shape.Area()
   return area
Example 1

shp1 = IrregularShape()
shp1.AddShape(Square(3))
shp1.AddShape(Triangle(4, 5))
shp1.AddShape(Square(10))
print shp1.Area()

========
Output:
119.0
Exercise 1 (5 Minutes)
Add another IrregularShape that has double
 the area of shp1 in the previous example,
 ONLY by using shp1 object that you have
 just created, not using any other shapes
Exercise 1 (Solution)
shp2 = IrregularShape()
shp2.AddShape(shp1)
shp2.AddShape(shp1)
print shp2.Area()



=====
Output:
238.0
Example 2
Type this SquareMatrix                 def addNumber(self, number):
                                           resultMatrix = SquareMatrix()
   class in your main file:
                                           matrixDimension = len(self.matrix)


                                           for rowIndex in range(0,matrixDimension):
#square matrix only
                                                                 newRow = []
class SquareMatrix:
                                                                 for columnIndex in range(0,matrixDimension):
    def __init__(self):
             self.matrix = []                        newRow.append(self.matrix[rowIndex][columnIndex]    +
                                           number)
    def appendRow(self, row):                                    resultMatrix.appendRow(newRow)
             self.matrix.append(row)
                                           return resultMatrix
    def printMatrix(self):
             for row in self.matrix:
                                                                                 Output:
                                       ================================          [-1, 1]
             print row                 mat = SquareMatrix()                      [8, 4]
                                       mat.appendRow([0, 2])
                                       mat.appendRow([9, 5])
                                       mat.addNumber(-1)
Example 2
#square matrix only
class SquareMatrix:
   def __init__(self):
         self.matrix = []


   def appendRow(self, row):
         self.matrix.append(row)


   def printMatrix(self):
         for row in self.matrix:
                            print row
Example 2
def addNumber(self, number):
   resultMatrix = SquareMatrix()
   matrixDimension = len(self.matrix)


   for rowIndex in range(0,matrixDimension):
                    newRow = []
                    for columnIndex in range(0,matrixDimension):
                    newRow.append(self.matrix[rowIndex][columnIndex]         + number)
                    resultMatrix.appendRow(newRow)


   return resultMatrix
================================
mat = SquareMatrix()                                               Output:
mat.appendRow([0, 2])                                              [-1, 1]
                                                                   [8, 4]
mat.appendRow([9, 5])
mat.addNumber(-1)
mat.printMatrix()
Example 2
This class represents a square matrix (equal row, column dimensions),
   the add number function


matrix data is filled by row, using the appendRow() function


addNumber() function adds a number to every element in the matrix
Exercise 2 (10 minutes)
Add a new fucntion add() that returns a new
 matrix which is the result of adding this matrix
 with another matrix:

mat1 = SquareMatrix()
mat1.appendRow([1, 2])    1   2   1 -2     2 0
mat1.appendRow([4, 5])
                          4   5   -5 1     -1 6
mat2 = SquareMatrix()
mat2.appendRow([1, -2])
mat2.appendRow([-5, 1])



mat3 = mat1.add(mat2)
mat3.printMatrix()
Exercise 2 (Solution)
def add(self, otherMatrix):
          resultMatrix = SquareMatrix()
          matrixDimension = len(self.matrix)
     for rowIndex in range(0,matrixDimension):
           newRow = []
           for columnIndex in range(0,matrixDimension):
                  newRow.append(self.matrix[rowIndex][columnIndex] + otherMatrix.matrix[rowIndex][columnIndex])
           resultMatrix.appendRow(newRow)
          return resultMatrix
=======================
mat1 = SquareMatrix()                         Fun: add 3 matrices in one line like this:
mat1.appendRow([1, 2])                        mat1.add(mat2).add(mat3).printMatrix()
mat1.appendRow([4, 5])



mat2 = SquareMatrix()
mat2.appendRow([1, -2])
mat2.appendRow([-5, 1])
Exercise 3 (10 minutes)
Add a new function mutliplyNumber(t), which multiplies a positive
integer t to the matrix, ONLY using the add(othermatrix) method


         1     -1                            5 -5
         -1     1            5               -5 5
Exercise 3 (Solution)
def multiplyNumber(self, times):
     result = self
     for i in range(0, times-1):
      result = result.add(self)
     return result
==========================

mat = SquareMatrix()
mat.appendRow([1, -1])
mat.appendRow([-1, 1])


mat.multiplyNumber(5)

More Related Content

PDF
Programs in array using SWIFT
vikram mahendra
Ā 
PDF
The Essence of the Iterator Pattern (pdf)
Eric Torreborre
Ā 
PDF
Numpy tutorial(final) 20160303
Namgee Lee
Ā 
PPTX
Introduction to Monads in Scala (2)
stasimus
Ā 
PPTX
The Essence of the Iterator Pattern
Eric Torreborre
Ā 
PDF
Introduction to NumPy for Machine Learning Programmers
Kimikazu Kato
Ā 
PDF
Baby Steps to Machine Learning at DevFest Lagos 2019
Robert John
Ā 
DOCX
Ml all programs
adnaanmohamed
Ā 
Programs in array using SWIFT
vikram mahendra
Ā 
The Essence of the Iterator Pattern (pdf)
Eric Torreborre
Ā 
Numpy tutorial(final) 20160303
Namgee Lee
Ā 
Introduction to Monads in Scala (2)
stasimus
Ā 
The Essence of the Iterator Pattern
Eric Torreborre
Ā 
Introduction to NumPy for Machine Learning Programmers
Kimikazu Kato
Ā 
Baby Steps to Machine Learning at DevFest Lagos 2019
Robert John
Ā 
Ml all programs
adnaanmohamed
Ā 

What's hot (19)

PPTX
Chapter 7.3
sotlsoc
Ā 
PPT
Chapter2
Krishna Kumar
Ā 
PDF
Matlab Graphics Tutorial
Cheng-An Yang
Ā 
PDF
What is TensorFlow and why do we use it
Robert John
Ā 
PDF
Gentlest Introduction to Tensorflow
Khor SoonHin
Ā 
PPTX
TensorFlow in Practice
indico data
Ā 
PPTX
(2015 06-16) Three Approaches to Monads
Lawrence Evans
Ā 
PDF
Matlab 1
asguna
Ā 
PDF
02 arrays
Rajan Gautam
Ā 
PDF
Gentlest Introduction to Tensorflow - Part 2
Khor SoonHin
Ā 
PDF
Gentlest Introduction to Tensorflow - Part 3
Khor SoonHin
Ā 
PPT
Chapter2
Nashra Akhter
Ā 
PPT
Scilab - Piecewise Functions
Jorge Jasso
Ā 
PDF
Introduction to Functions
Melanie Loslo
Ā 
PPT
Multi dimensional arrays
Aseelhalees
Ā 
PPT
Array
Malainine Zaid
Ā 
PPTX
Chapter 7.2
sotlsoc
Ā 
PDF
5. R basics
FAO
Ā 
PDF
Scala Functional Patterns
league
Ā 
Chapter 7.3
sotlsoc
Ā 
Chapter2
Krishna Kumar
Ā 
Matlab Graphics Tutorial
Cheng-An Yang
Ā 
What is TensorFlow and why do we use it
Robert John
Ā 
Gentlest Introduction to Tensorflow
Khor SoonHin
Ā 
TensorFlow in Practice
indico data
Ā 
(2015 06-16) Three Approaches to Monads
Lawrence Evans
Ā 
Matlab 1
asguna
Ā 
02 arrays
Rajan Gautam
Ā 
Gentlest Introduction to Tensorflow - Part 2
Khor SoonHin
Ā 
Gentlest Introduction to Tensorflow - Part 3
Khor SoonHin
Ā 
Chapter2
Nashra Akhter
Ā 
Scilab - Piecewise Functions
Jorge Jasso
Ā 
Introduction to Functions
Melanie Loslo
Ā 
Multi dimensional arrays
Aseelhalees
Ā 
Chapter 7.2
sotlsoc
Ā 
5. R basics
FAO
Ā 
Scala Functional Patterns
league
Ā 
Ad

Viewers also liked (7)

PPTX
Object oriented programming with python
Arslan Arshad
Ā 
PPTX
Python object oriented programming (lab2) (2)
iloveallahsomuch
Ā 
PDF
Python an-intro v2
Arulalan T
Ā 
PPTX
Advance OOP concepts in Python
Sujith Kumar
Ā 
PPTX
Python: Basic Inheritance
Damian T. Gordon
Ā 
PPTX
Python: Multiple Inheritance
Damian T. Gordon
Ā 
PPTX
Basics of Object Oriented Programming in Python
Sujith Kumar
Ā 
Object oriented programming with python
Arslan Arshad
Ā 
Python object oriented programming (lab2) (2)
iloveallahsomuch
Ā 
Python an-intro v2
Arulalan T
Ā 
Advance OOP concepts in Python
Sujith Kumar
Ā 
Python: Basic Inheritance
Damian T. Gordon
Ā 
Python: Multiple Inheritance
Damian T. Gordon
Ā 
Basics of Object Oriented Programming in Python
Sujith Kumar
Ā 
Ad

Similar to Python object oriented programming (lab2) (2) (20)

PDF
CE344L-200365-Lab2.pdf
UmarMustafa13
Ā 
PPTX
CSssssssssssss2030DE_Lab 1_final-111.pptx
TangChingXian
Ā 
PPT
Introduction to matlab
BilawalBaloch1
Ā 
PPTX
Python programming workshop session 3
Abdul Haseeb
Ā 
PDF
analysis of data structure design programs
SudarsanAssistantPro
Ā 
PPT
Topic20Arrays_Part2.ppt
adityavarte
Ā 
PDF
Arrays in python
Lifna C.S
Ā 
PDF
Lec 9 05_sept [compatibility mode]
Palak Sanghani
Ā 
PPTX
NumPy_Broadcasting Data Science - Python.pptx
JohnWilliam111370
Ā 
PPT
MATLAB-Introd.ppt
kebeAman
Ā 
PPTX
07+08slide.pptx
MURADSANJOUM
Ā 
PPT
Data Structure Midterm Lesson Arrays
Maulen Bale
Ā 
PDF
Coding test review2
SEMINARGROOT
Ā 
PDF
Coding test review
KyuyongShin
Ā 
PPTX
Chapter 7.1
sotlsoc
Ā 
PPT
Ch5 array nota
Hattori Sidek
Ā 
DOCX
More instructions for the lab write-up1) You are not obli.docx
gilpinleeanna
Ā 
PPT
Python High Level Functions_Ch 11.ppt
AnishaJ7
Ā 
PPT
Introduction to MATLAB
Damian T. Gordon
Ā 
PPTX
Arrays in Java
Abhilash Nair
Ā 
CE344L-200365-Lab2.pdf
UmarMustafa13
Ā 
CSssssssssssss2030DE_Lab 1_final-111.pptx
TangChingXian
Ā 
Introduction to matlab
BilawalBaloch1
Ā 
Python programming workshop session 3
Abdul Haseeb
Ā 
analysis of data structure design programs
SudarsanAssistantPro
Ā 
Topic20Arrays_Part2.ppt
adityavarte
Ā 
Arrays in python
Lifna C.S
Ā 
Lec 9 05_sept [compatibility mode]
Palak Sanghani
Ā 
NumPy_Broadcasting Data Science - Python.pptx
JohnWilliam111370
Ā 
MATLAB-Introd.ppt
kebeAman
Ā 
07+08slide.pptx
MURADSANJOUM
Ā 
Data Structure Midterm Lesson Arrays
Maulen Bale
Ā 
Coding test review2
SEMINARGROOT
Ā 
Coding test review
KyuyongShin
Ā 
Chapter 7.1
sotlsoc
Ā 
Ch5 array nota
Hattori Sidek
Ā 
More instructions for the lab write-up1) You are not obli.docx
gilpinleeanna
Ā 
Python High Level Functions_Ch 11.ppt
AnishaJ7
Ā 
Introduction to MATLAB
Damian T. Gordon
Ā 
Arrays in Java
Abhilash Nair
Ā 

Recently uploaded (20)

PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
Ā 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
Ā 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
Ā 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
Ā 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
Ā 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
Ā 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
Ā 
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
Ā 
PDF
This slide provides an overview Technology
mineshkharadi333
Ā 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
Ā 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
Ā 
PDF
Software Development Methodologies in 2025
KodekX
Ā 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
Ā 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
Ā 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
Ā 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
Ā 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
Ā 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
Ā 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
Ā 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
Ā 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
Ā 
L2 Rules of Netiquette in Empowerment technology
Archibal2
Ā 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
Ā 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
Ā 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
Ā 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
Ā 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
Ā 
This slide provides an overview Technology
mineshkharadi333
Ā 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
Ā 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
Ā 
Software Development Methodologies in 2025
KodekX
Ā 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
Ā 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
Ā 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
Ā 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
Ā 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
Ā 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
Ā 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
Ā 

Python object oriented programming (lab2) (2)

  • 1. Play with Python Lab2 Object Oriented Programming
  • 2. About Lecture 2 and Lab 2 Lecture 2 and its lab aims at covering Basic Object Oriented Programming concepts Classes, Constructor (__init__) and Objects
  • 3. Example 1 Create a new Project in shp1 = IrregularShape() Aptana "Lab2", then shp1.AddShape(Square(3)) add a new PyDev shp1.AddShape(Triangle(4, 5)) shp1.AddShape(Square(10)) module called main print shp1.Area() Write the following code ======== in your main file: Output: 119.0 class Square: def __init__(self, l): self.length = l def Area(self): return self.length**2 class Triangle: def __init__(self, b, h):
  • 4. Example 1 class Square: def __init__(self, l): self.length = l def Area(self): return self.length**2 class Triangle: def __init__(self, b, h): self.base = b self.height = h def Area(self): return 0.5*self.base*self.height
  • 5. Example 1 class IrregularShape: def __init__(self): self.shapes = [] def AddShape(self, shape): self.shapes.append(shape) def Area(self): area = 0 for shape in self.shapes: area += shape.Area() return area
  • 6. Example 1 shp1 = IrregularShape() shp1.AddShape(Square(3)) shp1.AddShape(Triangle(4, 5)) shp1.AddShape(Square(10)) print shp1.Area() ======== Output: 119.0
  • 7. Exercise 1 (5 Minutes) Add another IrregularShape that has double the area of shp1 in the previous example, ONLY by using shp1 object that you have just created, not using any other shapes
  • 8. Exercise 1 (Solution) shp2 = IrregularShape() shp2.AddShape(shp1) shp2.AddShape(shp1) print shp2.Area() ===== Output: 238.0
  • 9. Example 2 Type this SquareMatrix def addNumber(self, number): resultMatrix = SquareMatrix() class in your main file: matrixDimension = len(self.matrix) for rowIndex in range(0,matrixDimension): #square matrix only newRow = [] class SquareMatrix: for columnIndex in range(0,matrixDimension): def __init__(self): self.matrix = [] newRow.append(self.matrix[rowIndex][columnIndex] + number) def appendRow(self, row): resultMatrix.appendRow(newRow) self.matrix.append(row) return resultMatrix def printMatrix(self): for row in self.matrix: Output: ================================ [-1, 1] print row mat = SquareMatrix() [8, 4] mat.appendRow([0, 2]) mat.appendRow([9, 5]) mat.addNumber(-1)
  • 10. Example 2 #square matrix only class SquareMatrix: def __init__(self): self.matrix = [] def appendRow(self, row): self.matrix.append(row) def printMatrix(self): for row in self.matrix: print row
  • 11. Example 2 def addNumber(self, number): resultMatrix = SquareMatrix() matrixDimension = len(self.matrix) for rowIndex in range(0,matrixDimension): newRow = [] for columnIndex in range(0,matrixDimension): newRow.append(self.matrix[rowIndex][columnIndex] + number) resultMatrix.appendRow(newRow) return resultMatrix ================================ mat = SquareMatrix() Output: mat.appendRow([0, 2]) [-1, 1] [8, 4] mat.appendRow([9, 5]) mat.addNumber(-1) mat.printMatrix()
  • 12. Example 2 This class represents a square matrix (equal row, column dimensions), the add number function matrix data is filled by row, using the appendRow() function addNumber() function adds a number to every element in the matrix
  • 13. Exercise 2 (10 minutes) Add a new fucntion add() that returns a new matrix which is the result of adding this matrix with another matrix: mat1 = SquareMatrix() mat1.appendRow([1, 2]) 1 2 1 -2 2 0 mat1.appendRow([4, 5]) 4 5 -5 1 -1 6 mat2 = SquareMatrix() mat2.appendRow([1, -2]) mat2.appendRow([-5, 1]) mat3 = mat1.add(mat2) mat3.printMatrix()
  • 14. Exercise 2 (Solution) def add(self, otherMatrix): resultMatrix = SquareMatrix() matrixDimension = len(self.matrix) for rowIndex in range(0,matrixDimension): newRow = [] for columnIndex in range(0,matrixDimension): newRow.append(self.matrix[rowIndex][columnIndex] + otherMatrix.matrix[rowIndex][columnIndex]) resultMatrix.appendRow(newRow) return resultMatrix ======================= mat1 = SquareMatrix() Fun: add 3 matrices in one line like this: mat1.appendRow([1, 2]) mat1.add(mat2).add(mat3).printMatrix() mat1.appendRow([4, 5]) mat2 = SquareMatrix() mat2.appendRow([1, -2]) mat2.appendRow([-5, 1])
  • 15. Exercise 3 (10 minutes) Add a new function mutliplyNumber(t), which multiplies a positive integer t to the matrix, ONLY using the add(othermatrix) method 1 -1 5 -5 -1 1 5 -5 5
  • 16. Exercise 3 (Solution) def multiplyNumber(self, times): result = self for i in range(0, times-1): result = result.add(self) return result ========================== mat = SquareMatrix() mat.appendRow([1, -1]) mat.appendRow([-1, 1]) mat.multiplyNumber(5)