We will now look at how we create classes in Python in our calculator
module.
First, we will create the Operation
class. It is used to represent a single operation that can be performed by the Calculator
class. Here, we are inheriting from the object
class, which is the base class from which all the objects inherit in Python.
class Operation(object): _operation = None
The __init__
function is the constructor of the class. It is called when a new instance of a class is created. Here, we will use it to validate the function that is provided by a parameter and store it in the class.
def __init__(self, name): if name not in ["add", "subtract", "multiply", "divide"]: raise ValueError("%s is not a valid operation" % (name)) self._operation = name
Methods in the Python classes are required to take a parameter typically named self
. This parameter is the instance of the class that the function was called on, and it must be used when calling...