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

What's hot (19)

Chapter 7.3
Chapter 7.3Chapter 7.3
Chapter 7.3
sotlsoc
 
Chapter2
Chapter2Chapter2
Chapter2
Krishna Kumar
 
Matlab Graphics Tutorial
Matlab Graphics TutorialMatlab Graphics Tutorial
Matlab Graphics Tutorial
Cheng-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 it
Robert John
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to Tensorflow
Khor SoonHin
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practice
indico 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 Monads
Lawrence Evans
 
Matlab 1
Matlab 1Matlab 1
Matlab 1
asguna
 
02 arrays
02 arrays02 arrays
02 arrays
Rajan Gautam
 
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2
Khor SoonHin
 
Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3
Khor SoonHin
 
Chapter2
Chapter2Chapter2
Chapter2
Nashra Akhter
 
Scilab - Piecewise Functions
Scilab - Piecewise FunctionsScilab - Piecewise Functions
Scilab - Piecewise Functions
Jorge Jasso
 
Introduction to Functions
Introduction to FunctionsIntroduction to Functions
Introduction to Functions
Melanie Loslo
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
Aseelhalees
 
Array
ArrayArray
Array
Malainine Zaid
 
Chapter 7.2
Chapter 7.2Chapter 7.2
Chapter 7.2
sotlsoc
 
5. R basics
5. R basics5. R basics
5. R basics
FAO
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
league
 
Chapter 7.3
Chapter 7.3Chapter 7.3
Chapter 7.3
sotlsoc
 
Matlab Graphics Tutorial
Matlab Graphics TutorialMatlab Graphics Tutorial
Matlab Graphics Tutorial
Cheng-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 it
Robert John
 
Gentlest Introduction to Tensorflow
Gentlest Introduction to TensorflowGentlest Introduction to Tensorflow
Gentlest Introduction to Tensorflow
Khor SoonHin
 
TensorFlow in Practice
TensorFlow in PracticeTensorFlow in Practice
TensorFlow in Practice
indico 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 Monads
Lawrence Evans
 
Matlab 1
Matlab 1Matlab 1
Matlab 1
asguna
 
Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2Gentlest Introduction to Tensorflow - Part 2
Gentlest Introduction to Tensorflow - Part 2
Khor SoonHin
 
Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3Gentlest Introduction to Tensorflow - Part 3
Gentlest Introduction to Tensorflow - Part 3
Khor SoonHin
 
Scilab - Piecewise Functions
Scilab - Piecewise FunctionsScilab - Piecewise Functions
Scilab - Piecewise Functions
Jorge Jasso
 
Introduction to Functions
Introduction to FunctionsIntroduction to Functions
Introduction to Functions
Melanie Loslo
 
Multi dimensional arrays
Multi dimensional arraysMulti dimensional arrays
Multi dimensional arrays
Aseelhalees
 
Chapter 7.2
Chapter 7.2Chapter 7.2
Chapter 7.2
sotlsoc
 
5. R basics
5. R basics5. R basics
5. R basics
FAO
 
Scala Functional Patterns
Scala Functional PatternsScala Functional Patterns
Scala Functional Patterns
league
 

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

CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
UmarMustafa13
 
CSssssssssssss2030DE_Lab 1_final-111.pptx
CSssssssssssss2030DE_Lab 1_final-111.pptxCSssssssssssss2030DE_Lab 1_final-111.pptx
CSssssssssssss2030DE_Lab 1_final-111.pptx
TangChingXian
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
BilawalBaloch1
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
Abdul Haseeb
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
adityavarte
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
Lifna 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.pptx
JohnWilliam111370
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
kebeAman
 
07+08slide.pptx
07+08slide.pptx07+08slide.pptx
07+08slide.pptx
MURADSANJOUM
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Coding test review2
Coding test review2Coding test review2
Coding test review2
SEMINARGROOT
 
Coding test review
Coding test reviewCoding test review
Coding test review
KyuyongShin
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
Ch5 array nota
Ch5 array notaCh5 array nota
Ch5 array nota
Hattori Sidek
 
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
gilpinleeanna
 
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
AnishaJ7
 
Introduction to MATLAB
Introduction to MATLABIntroduction to MATLAB
Introduction to MATLAB
Damian T. Gordon
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Abhilash Nair
 
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
PranavAnil9
 
CE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdfCE344L-200365-Lab2.pdf
CE344L-200365-Lab2.pdf
UmarMustafa13
 
CSssssssssssss2030DE_Lab 1_final-111.pptx
CSssssssssssss2030DE_Lab 1_final-111.pptxCSssssssssssss2030DE_Lab 1_final-111.pptx
CSssssssssssss2030DE_Lab 1_final-111.pptx
TangChingXian
 
Introduction to matlab
Introduction to matlabIntroduction to matlab
Introduction to matlab
BilawalBaloch1
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
Abdul Haseeb
 
Topic20Arrays_Part2.ppt
Topic20Arrays_Part2.pptTopic20Arrays_Part2.ppt
Topic20Arrays_Part2.ppt
adityavarte
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
Lifna 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.pptx
JohnWilliam111370
 
MATLAB-Introd.ppt
MATLAB-Introd.pptMATLAB-Introd.ppt
MATLAB-Introd.ppt
kebeAman
 
Data Structure Midterm Lesson Arrays
Data Structure Midterm Lesson ArraysData Structure Midterm Lesson Arrays
Data Structure Midterm Lesson Arrays
Maulen Bale
 
Coding test review2
Coding test review2Coding test review2
Coding test review2
SEMINARGROOT
 
Coding test review
Coding test reviewCoding test review
Coding test review
KyuyongShin
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
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
gilpinleeanna
 
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
AnishaJ7
 
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
PranavAnil9
 
Ad

Recently uploaded (20)

Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Enabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FMEEnabling BIM / GIS integrations with Other Systems with FME
Enabling BIM / GIS integrations with Other Systems with FME
Safe Software
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdfArtificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and ImplementationAI Agents in Logistics and Supply Chain Applications Benefits and Implementation
AI Agents in Logistics and Supply Chain Applications Benefits and Implementation
Christine Shepherd
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
Ad

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)