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

What's hot

Chapter 7.3
Chapter 7.3Chapter 7.3
Chapter 7.3sotlsoc
 
Matlab Graphics Tutorial
Matlab Graphics TutorialMatlab Graphics Tutorial
Matlab Graphics TutorialCheng-An Yang
 
What is TensorFlow and why do we use it
What is TensorFlow and why do we use itWhat is TensorFlow and why do we use it
What is TensorFlow and why do we use itRobert John
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowKhor SoonHin
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practiceindico data
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to MonadsLawrence Evans
 
Matlab 1
Matlab 1Matlab 1
Matlab 1asguna
 
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Khor SoonHin
 
Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Khor SoonHin
 
Scilab - Piecewise Functions
Scilab - Piecewise FunctionsScilab - Piecewise Functions
Scilab - Piecewise FunctionsJorge Jasso
 
Introduction to Functions
Introduction to FunctionsIntroduction to Functions
Introduction to FunctionsMelanie Loslo
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arraysAseelhalees
 
Chapter 7.2
Chapter 7.2Chapter 7.2
Chapter 7.2sotlsoc
 
5. R basics
5. R basics5. R basics
5. R basicsFAO
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patternsleague
 

What's hot (19)

Chapter 7.3
Chapter 7.3Chapter 7.3
Chapter 7.3
 
Chapter2
Chapter2Chapter2
Chapter2
 
Matlab Graphics Tutorial
Matlab Graphics TutorialMatlab Graphics Tutorial
Matlab Graphics Tutorial
 
What is TensorFlow and why do we use it
What is TensorFlow and why do we use itWhat is TensorFlow and why do we use it
What is TensorFlow and why do we use it
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to Tensorflow
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practice
 
(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads(2015 06-16) Three Approaches to Monads
(2015 06-16) Three Approaches to Monads
 
Matlab 1
Matlab 1Matlab 1
Matlab 1
 
02 arrays
02 arrays02 arrays
02 arrays
 
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2
 
Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3
 
Chapter2
Chapter2Chapter2
Chapter2
 
Scilab - Piecewise Functions
Scilab - Piecewise FunctionsScilab - Piecewise Functions
Scilab - Piecewise Functions
 
Introduction to Functions
Introduction to FunctionsIntroduction to Functions
Introduction to Functions
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
 
Array
ArrayArray
Array
 
Chapter 7.2
Chapter 7.2Chapter 7.2
Chapter 7.2
 
5. R basics
5. R basics5. R basics
5. R basics
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
 

Viewers also liked

Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
Python object oriented programming (lab2) (2)
Python object oriented programming (lab2) (2)Python object oriented programming (lab2) (2)
Python object oriented programming (lab2) (2)iloveallahsomuch
 
Python an-intro v2
Python an-intro v2Python an-intro v2
Python an-intro v2Arulalan T
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple InheritanceDamian T. Gordon
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 

Viewers also liked (7)

Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Python object oriented programming (lab2) (2)
Python object oriented programming (lab2) (2)Python object oriented programming (lab2) (2)
Python object oriented programming (lab2) (2)
 
Python an-intro v2
Python an-intro v2Python an-intro v2
Python an-intro v2
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Python: Multiple Inheritance
Python: Multiple InheritancePython: Multiple Inheritance
Python: Multiple Inheritance
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 

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

CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfUmarMustafa13
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlabBilawalBaloch1
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3Abdul Haseeb
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptadityavarte
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonLifna C.S
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Palak Sanghani
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxJohnWilliam111370
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.pptkebeAman
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysMaulen Bale
 
Coding test review2
Coding test review2Coding test review2
Coding test review2SEMINARGROOT
 
Coding test review
Coding test reviewCoding test review
Coding test reviewKyuyongShin
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1sotlsoc
 
More instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxMore instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxgilpinleeanna
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptAnishaJ7
 
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfComputer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfPranavAnil9
 

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

CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]Lec 9 05_sept [compatibility mode]
Lec 9 05_sept [compatibility mode]
 
NumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptxNumPy_Broadcasting Data Science - Python.pptx
NumPy_Broadcasting Data Science - Python.pptx
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
 
Coding test review2
Coding test review2Coding test review2
Coding test review2
 
Coding test review
Coding test reviewCoding test review
Coding test review
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
 
More instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docxMore instructions for the lab write-up1) You are not obli.docx
More instructions for the lab write-up1) You are not obli.docx
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdfComputer Science CS Project Matrix CBSE Class 12th XII .pdf
Computer Science CS Project Matrix CBSE Class 12th XII .pdf
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 

Recently uploaded

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

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)