Reader small image

You're reading from  Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)

Product typeBook
Published inSep 2015
Reading LevelBeginner
Publisher
ISBN-139781783551590
Edition1st Edition
Languages
Right arrow
Author (1)
Dan Nixon
Dan Nixon
author image
Dan Nixon

Dan Nixon is a software and electronics engineer living in the north of England. He has past experience of creating software for data analysis, process control, and business intelligence applications. In most of these projects, Python was one of the main languages used. Dan previously authored another book on the uses of the Raspberry Pi, called Raspberry Pi Blueprints, and has worked on many personal projects that use both Python and the Raspberry Pi.
Read more about Dan Nixon

Right arrow

Chapter 4. Understanding Object-oriented Programming and Threading

In this chapter, we will look at how object-oriented programming (OOP) can be done using Python, how code can be arranged into modules, and how these modules can be used in scripts.

We will also have a quick look at how multithreading can be used within a Python script in order to perform multiple operations simultaneously within the program.

In this chapter, we will cover the following topics:

  • Object-oriented programming

  • Classes in Python

  • Threading

Object-oriented programming


Object-oriented programming is a paradigm in which the program is structured around several objects rather than actions or functionality. The main difference is that in the procedural programming type that we have been using so far in the book, the focus is on the processing that is being carried out, whereas in object-oriented programming, the focus is on the data being processed.

To demonstrate this, we will write a simple module that provides an interface similar to a conventional calculator, that is, input in the form of a series of numerical values and operations.

The structure for this module is shown in the following Unified Modeling Language (UML) (www.uml.org) diagram:

Here each block represents a class, with the second square representing the member variables of the class and the bottom representing the functions.

An arrow indicates that a class inherits from the class it points to. This essentially means that the class inherits all of the parent class...

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

Threading


Multithreading allows an application to have multiple flows of control that are executed simultaneously. On the Raspberry Pi, this can be useful in applications that need to monitor the General Purpose Input and Output (GPIO) pins to react to the changes in switch and sensor states.

Multithreading is a large subject that can take a long time to cover completely, hence only a couple of the Python classes in the threading module will be covered here. However, the full documentation for this module is available at https://docs.python.org/2/library/threading.html.

First, we will import the required modules for the functionality that we will be using and will set up the default logger so that we can see the process ID when a log is written to it. You don't need to worry about this now, as we will be going over the logging framework in Python in a later chapter.

import logging
import threading
import time
logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s...

Summary


In this chapter, we looked at the object-oriented programming paradigm and how it can benefit applications, and the way that classes can be combined into modules and used in other scripts.

We also had a brief introduction to multithreading and the best practices for ensuring data validity between the threads that access shared data.

In the next chapter, we will have a look at the setuptools utility and see how it can be used to package the Python code for distribution to multiple systems, and how it can help manage dependencies on the other libraries.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Getting Started with Python and Raspberry Pi (Redirected from Learning Python By Developing Raspberry Pi Applications)
Published in: Sep 2015Publisher: ISBN-13: 9781783551590
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Dan Nixon

Dan Nixon is a software and electronics engineer living in the north of England. He has past experience of creating software for data analysis, process control, and business intelligence applications. In most of these projects, Python was one of the main languages used. Dan previously authored another book on the uses of the Raspberry Pi, called Raspberry Pi Blueprints, and has worked on many personal projects that use both Python and the Raspberry Pi.
Read more about Dan Nixon