7 Classes
Classes in Python¶
So far we have gone over built in variable types like string, integer, float, boolean, and list. Now we turn to the final variable type that is called a class
.
Classes do not exist by default but need to be create by us, the programmers!
Here is a simple example.
class MyClass():
def __init__(self):
# define a member variable named aVariable
self.aVariable = 1.1
def getVariable(self):
"""Get the current value.
"""
return self.aVariable
def setVariable(self, newValue):
"""Set the current value.
"""
self.aVariable = newValue
A particular thing about classes is they use a Python keyword self
. This lets Python know you are defining something for the class you are in.
Each class can have its own local variables like self.aVariable
Each class can have its own functions like def getVariable(self)
Variables defined in a class are called member variables
. Functions defined in a class are called member functions
.
In our example, we made a class named MyClass
. It has one member variable, aVariable
. It also has two member functions, getVariable()
and setVariable()
Now lets use the class.
# we create a variable of type MyClass
myClassVariable = MyClass()
# we can then call member functions on our new type MyClass
currentValue = myClassVariable.getVariable()
print(currentValue)
myNewValue = 20
myClassVariable.setVariable(myNewValue)
currentValue = myClassVariable.getVariable()
print(currentValue)
1.1 20
Recap on classes¶
You won't be required to write your own classes, we will use classes written for this IOT class.
Our code that will run on the Arduino Nano uses classes for most everything. They allow us to group similar ideas into one set of code.
When you use a class you are using object oriented programming
versus functional programming
.
Some examples of classes we will use are:
- iotButton - Implements all the code to listen for button pushes.
- iotLed - Implements all the code to control an LED.
Classes are useful for what is called data abstraction
. As the programmer, you don't need to know the details of how a class is implemented, you only need to know about the member function(s) it defines.
When done properly, this system provides an Application Programming Interface
or API.
Other example classes we will use demonstrate this well.
- iotWifi - A class to abstract away all the details of connecting to Wifi.
- iotMqtt - A class to abstract away all the details of using Mqtt to publish and subscribe to data on Adafruit IO.