!!! Classes and Methods

This is __Exercise 3__ of the [Micro Python Tutorial].

We can define __classes__ in Python. Classes are defined globally, within the file/module as they begin in column 0.

Within a class its functions are called __methods__. Unlike functions, methods are defined within the scope of the class and are therefore indented within the class's block.

A class has a constructor, a special method named {{{__init__}}}. All special methods in Python are surrounded by double underscores. (There are more of these but we'll get to them later.)

!motor_controller.py
%%python {{{

from motor import Motor

class MotorController:

    def __init__(self):
      self.port_forward_motor = Motor('pfwd')
      self.stbd_forward_motor = Motor('sfwd')
      print('motor controller ready.')
}}}
%%

!motor.py:
%%python {{{
class Motor:
    def __init__(self, name):
        self.motor_name = name
        self.motor_speed = 0
        print('motor {} ready.'.format(self.motor_name))
        
    def set_speed(self, speed):
        self.motor_speed = speed
        print("speed: {}".format(speed))

    def get_speed(self):
        return self.motor_speed
}}}
%%


!main.py:
%%python {{{

from motor_controller import MotorController

try:

    motor_ctrl = MotorController()


except Exception as ex:
    print('an error occurred: {}'.format(ex))
finally:
    print('complete.')
}}}
%%

----
__Previous:__ [MicroPython Tutorial Exercise 2|MicroPythonTutorialExercise02]: functions \\
__Next:__ [MicroPython Tutorial Exercise 4|MicroPythonTutorialExercise04]: using classes