.. _ch04-python-oop: =============================================================== 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: .. literalinclude:: ./codes/oop1.py :language: python :linenos: 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) in () ----> 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: .. literalinclude:: ./codes/oop2.py :language: python :linenos: 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.