Book Image

Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)

By : Dan Nixon
Book Image

Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)

By: Dan Nixon

Overview of this book

Table of Contents (18 chapters)
Getting Started with Python and Raspberry Pi
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Classes in Python


We will now look at how we create classes in Python in our calculator module.

Operation.py

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...