A short example of object-oriented programming (OOP) in Python

Python supports object-oriented programming (OOP). The goals of OOP are:

  • to organize the code, and
  • to re-use code in similar contexts.

Here is a small example: we create a Student class, which is an object gathering several custom functions (methods) and variables (attributes), we will be able to use:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
"""
lectureNote/chapters/chapt04/codes/oop1.py

A very short example of OOP:
This example code is originally taken from

   http://www.scipy-lectures.org/intro/language/oop.html

"""

class Student:
    def __init__(self, first_name, last_name):
        self.first_name = first_name
        self.last_name = last_name
        self.full_name = first_name + ' ' + last_name
    def set_age(self, age):
        self.age = age
    def set_major(self, major):
        self.major = major
    def set_minor(self,minor):
        self.minor = minor


if __name__ == '__main__' :

    jenny = Student('Jenny','Evans')
    jenny.set_age(21)
    jenny.set_major('physics')

    print(jenny.full_name)
    print(jenny.age)
    print(jenny.major)

    jenny.set_minor('math')
    print(jenny.minor)

In this example, the Student class has __init__, set_age and set_major, set_minor methods. Its attributes are first_name, last_name, age, major and minor. We can call these methods and attributes with the following notation: classinstance.method or classinstance.attribute. The __init__ constructor is a special method we call with: MyClass(init parameters if any).

With a class that defines __init__() method, class instantiation automatically invokes __init__() for a newly created class instance. This allows you to create a new class instance

superman = Student('Clark','Kent')

Try and see what happens if you don’t provide two inputs of first and last names

In [1]: from oop1 import Student

In [2]: superman = Student()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-a97011fc17eb> in <module>()
----> 1 superman = Student()

TypeError: __init__() takes exactly 3 arguments (1 given)

Back to the example now. The result of running this routine looks like

$ python oop1.py
Jenny Evans
physics

Now, suppose we want to create a new class MasterStudent with the same methods and attributes as the previous one, but with an additional internship attribute. We won’t copy the previous class, but inherit from it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
"""
lectureNote/chapters/chapt04/codes/oop2.py

A very short example of OOP:
This example code is originally taken from

   http://www.scipy-lectures.org/intro/language/oop.html

"""


from oop1 import Student

class MasterStudent(Student):
    internship = 'Google, 2013-2014'

if __name__ == '__main__' :

    james = MasterStudent('James','Morgan')
    james.set_age(23)
    james.set_major('applied math')
    james.set_minor('music')


    print(james.first_name)
    print(james.last_name)
    print(james.full_name)
    print(james.age)
    print(james.major)
    print(james.minor)
    print(james.internship)

The MasterStudent class inherited from the Student attributes and methods. Thanks to classes and object-oriented programming, we can organize code with different classes corresponding to different objects we encounter (an Experiment class, an Image class, a Flow class, etc.), with their own methods and attributes. Then we can use inheritance to consider variations around a base class and reuse code. For examples, from a Flow base class, we can create derived StokesFlow, TurbulentFlow, PotentialFlow, etc.

Executing oop2.py will give

$ python oop2.py
James
Morgan
James Morgan
23
applied math
music
Google, 2013-2014

More to read:

Exercise

  1. Modify the above example, oop2.py, so that it can set two attributes, internship_where and internship_when in the MasterStudent class.
  2. Print the two new attributes.