Learn 3: Create Your First Class
2. Creating a Variable Container Class
In previous missions we wrote code that was not contained within a function definition in the Main Code cell. This can see and use all globally scoped variables in the program.
In this mission we will be wrapping this code inside a main() function that we will trigger from a button click. This means that all globally scoped variables will have to be declared as global at the beginning of the function definition to be usable by our code. As we like to use a lot of variables this could get messy!
Objects can come to our rescue here. To make things simpler we can do the following:
- package all our variables up into a single globally scoped container class
- instantiate this class in the same way as the robot and sensors
- declare the container class instance as a single global variable in all our functions
All our variables will then be accessible as class attributes from within the functions.