Objects and Classes Python
Objects and Classes Python
Programming - 2
Recap
• Object Orientation
– merge data and functions (that operate on the
data) together into classes
– class is like a blue print of an object
– objects are instances of a class
– typically two kinds of members in a class
• members that store data are attributes
• members that are functions are methods
Exmple 1: Class Coordinate
Keyword to indicate declaration of a class
Exmple 1: Class Coordinate
Name of a class
Exmple 1: Class Coordinate
Parent class
Exmple 1: Class Coordinate
special method
constructor
Exmple 1: Class Coordinate
method distance
Exmple 1: Class Coordinate
Equivalent
Operator Overloading
What the operator does, depends on the objects
it operates on. For example:
>>> a = "Hello "; b = "World"
>>> a + b # concatenation
'Hello World'
>>> c = 10; d = 20
>>> c + d # addition
30
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Class Inheritance
Sometimes, we need classes that share certain (or very
many, or all) attributes but are slightly different.
• Example 1: Geometry
a point (in 2 dimensions) has an x and y attribute
a circle is a point with a radius
a cylinder is a circle with a height
• Example 2: People at universities
A person has an address.
A student is a person and selects modules.
A lecturer is a person with teaching duties.
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Class Inheritance
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Class Inheritance
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Class Inheritance: Another Example
Source:Computational Science and Engineering in Python by Hans Fangohr, Engineering and Environment, University of Southampton,
United Kingdom
Class Inheritance: Another Example
Source:Computational Science and Engineering in Python by Hans Fangohr, Engineering and Environment, University of Southampton,
United Kingdom
Class Inheritance: Another Example
Source:Computational Science and Engineering in Python by Hans Fangohr, Engineering and Environment, University of Southampton,
United Kingdom