How to Use Advanced Object-Oriented Python

In this tutorial, we are going to learn advanced concepts for object-oriented programming using Python.

Prerequisites

Writing Getters and Setters

Let’s learn about getters and setters – they’re like security guards for your robot’s information! Think of them as special functions that help you safely check and change your robot’s settings. 

Just like you wouldn’t want anyone to accidentally set your robot’s speed to a dangerous level, getters and setters help protect your robot’s information and make sure it’s changed in the right way.

First, create a file called robot_settings.py inside the following folder: ~/Documents/python_tutorial.

Define a class named Robot that will help us manage the speed and battery level, which are common attributes in robotics:

class Robot:
    def __init__(self, speed=0, battery=100):
        self._speed = speed
        self._battery = battery

    def get_speed(self):
        return self._speed

    def set_speed(self, value):
        if value < 0:
            raise ValueError("Speed cannot be negative")
        self._speed = value

    def get_battery(self):
        return self._battery

    def set_battery(self, value):
        if not (0 <= value <= 100):
            raise ValueError("Battery must be between 0 and 100")
        self._battery = value

This code snippet introduces get and set methods for speed and battery level. The setters include validations to ensure the values are within acceptable ranges, which is essential for maintaining the safety and functionality of your robot.

Next, run a simple test to see these getters and setters in action. 

Add the following test code at the end of your script:

robot = Robot()
print("Initial Speed:", robot.get_speed())
robot.set_speed(5)
print("Updated Speed:", robot.get_speed())

try:
    robot.set_battery(150)
except ValueError as e:
    print(e)

Now, run the code:

1-robot-settings

You should see the outputs corresponding to the robot’s speed updates and any error messages related to battery level adjustments.

Using Inheritance

Let’s talk about inheritance in Python, a topic we briefly covered in the previous tutorial.

Inheritance is like creating a family tree of robots. Imagine you design a basic robot with common features. Then, just like how children inherit traits from their parents, you can create new types of robots that automatically get all the abilities of the basic robot, plus their own special features. This saves you from having to write the same code over and over again.

Create a new file called robot_inheritance.py inside the following folder: ~/Documents/python_tutorial.

Begin by defining a base class called Robot that will contain common attributes and methods that any robot might need:

class Robot:
    def __init__(self, name):
        self.name = name

    def greet(self):
        print(f"Hello, I am {self.name}.")

Now, let’s use inheritance to create a specialized type of robot. We’ll define a class CleaningRobot that inherits from Robot:

class CleaningRobot(Robot):
    def clean(self):
        print("Cleaning in progress...")

Notice how CleaningRobot doesn’t redefine the __init__ method or the greet method but inherits them from the Robot class. It does, however, add a new method, clean, which is specific to cleaning robots.

Now let’s add this test code at the end of your script to create an instance of CleaningRobot and use its methods:

my_robot = CleaningRobot("RoboCleaner")
my_robot.greet()
my_robot.clean()

Now, run the script.

2-robot-inheritance

You should see the greeting from the robot followed by the cleaning message. This demonstrates how the CleaningRobot uses functionality from the Robot base class while adding its own unique behavior.

Practicing Polymorphism

Let’s take a look at another key concept in object-oriented programming: polymorphism. 

Polymorphism literally means “many forms”.

Imagine you have a television remote control with a “power” button that works on different TVs. Just like how different television classes (Samsung, LG, or Sony) all understand the same power command, different robot classes can share common commands too. This is polymorphism in action – we can treat different kinds of objects (like our different robot types) as if they were the same basic type (like a general “robot” class). 

For example, all our robots might understand the command “move forward,” but each robot class implements it differently: a walking robot takes steps, while a wheeled robot rolls forward. Same command name, different behaviors!

Create a new file named polymorphism_example.py inside the following folder: ~/Documents/python_tutorial.

Start by defining a base class called Robot with the following method:

class Robot:
    def __init__(self, name):
        self.name = name

    def perform_task(self):
        print(f"{self.name} performs a generic task.")

Now, let’s define two subclasses that inherit from Robot but perform tasks differently, demonstrating polymorphism:

class CleaningRobot(Robot):
    def perform_task(self):
        print(f"{self.name} is cleaning the area.")

class PaintingRobot(Robot):
    def perform_task(self):
        print(f"{self.name} is painting the wall.")

Each subclass has its own implementation of the perform_task method, tailored to what the specific robot is supposed to do.

Now add this test code at the end of your script to create instances of each robot and call their task method:

robots = [CleaningRobot("Cleany"), PaintingRobot("Painty")]
for robot in robots:
    robot.perform_task()

Now, run the script.

3-polymorphism

You should see each robot performing its specific task, demonstrating how polymorphism allows us to use a common method in different contexts.

Working with Magic Methods

Now let’s explore a concept of Python programming that can significantly enhance your coding, especially when working with classes in robotics: magic methods, also known as dunder methods. 

Magic methods are special methods that start and end with double underscores. They allow us to implement functionality that mimics the behavior of built-in types and elegantly interact with different Python operations.

Create a new file named magic_methods.py inside the following folder: ~/Documents/python_tutorial.

We’ll begin by defining a class called Robot that utilizes some common magic methods:

class Robot:
    def __init__(self, name, battery_life):
        self.name = name
        self.battery_life = battery_life

    def __str__(self):
        return f"{self.name} (Battery life: {self.battery_life} hours)"

    def __len__(self):
        return self.battery_life

    def __add__(self, other):
        if isinstance(other, Robot):
            return Robot(f"{self.name}&{other.name}", self.battery_life + other.battery_life)
        raise ValueError("Can only add another Robot")

In this snippet, we define three magic methods:

__str__: customizes the string representation of our objects, making it more informative.

__len__: allows us to use Python’s len() function to get the battery life of the robot.

__add__: enables us to “add” two robots together to create a new robot with combined names and battery life.

Now add the following test code at the end of your script:

robot1 = Robot("Robo-One", 5)
robot2 = Robot("Robo-Two", 3)
print(robot1)
print("Battery life of", robot1.name, "is", len(robot1), "hours")
combined_robot = robot1 + robot2
print(combined_robot)

Run your code.

4-magic-methods

You should see the string representations of the robots, their individual battery lives, and the details of the combined robot. 

That concludes our overview of magic methods. Thanks, and I’ll see you in the next tutorial.

Keep building!

How to Read and Write Files in Python

In this tutorial, we are going to learn how to work with files in Python. Handling files is a fundamental skill in programming, essential for tasks like logging data, saving configurations, and processing input in robotics applications.

Prerequisites

Working with Files: Create, Write, Close, Append, and Read

Let’s cover how to create, write, close, append, and read files using Python’s built-in functions. 

Creating and Writing to a File

To create and write to a file, you can use Python’s open function with the ‘w’ mode. This mode creates the file if it does not exist and overwrites it if it does.

Create a file called file_handling.py inside the following folder: ~/Documents/python_tutorial.

Write the following code:

file = open('example.txt', 'w')
file.write('Hello, world!')
file.close()

It’s important to close the file when you’re done with it. Closing the file ensures that all changes are saved and frees up system resources.

Appending to a File

If you want to add content to a file without overwriting the existing content, you use the ‘a’ mode with the open function.

file = open('example.txt', 'a')
file.write('\nAdding a second line.')
file.close()

Reading from a File

To read the contents of a file, you use the ‘r’ mode with open. There are several methods to read, such as read(), readline(), which reads one line at a time, and readlines(), which returns a list of lines.

file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()

Using the with Statement

While using open() and close(), it’s safer to handle files with a context manager using the with statement. This ensures that the file is properly closed after its suite finishes, even if an exception occurs.

with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

You should see the content of example.txt printed, which now includes both the original line and the appended line.

1-file-handling
2-example-txt

In robotics, file handling is important for tasks such as storing sensor readings, saving configuration settings, or logging events for diagnostics. Efficient file management can help maintain the integrity and performance of robotic systems.

That’s it for this tutorial on working with files in Python. Thanks, and I’ll see you in the next tutorial.

Keep building!

How to Create Classes and Objects in Python

In this tutorial, we are going to learn about one of the core concepts of object-oriented programming: classes and objects. 

Understanding how to use classes and objects is essential for structuring robust and maintainable code in robotics, where you often model real-world entities like robots, sensors, and actuators.

Prerequisites

Getting Comfortable with Classes and Objects

Let’s start by defining what a class is. Think of a class like a recipe for making cookies. Just as a recipe tells us what ingredients we need (these are called variables or attributes in programming) and what steps to follow (these are called methods or functions in programming), a class defines both the data and the actions that our program can use. The recipe itself isn’t a cookie – it’s just instructions, just like a class is just code until we use it.

An object is when you actually make the cookies using your recipe – in programming terms, we call this “instantiating a class.” When you just write down a recipe (define a class), you’re not using any real ingredients or kitchen space yet (no computer memory is used). But when you start baking (create an object), that’s when you use real ingredients and take up real counter space (the computer allocates actual memory for your object). Each batch of cookies you make from the same recipe is like creating a new object from your class – they use the same instructions but are separate, physical things in your kitchen (separate spots in computer memory).

Let’s create a simple class called Robot. This class will have some basic attributes like name and color, and a method that allows the robot to introduce itself.

Create a program called robot_class.py inside the following folder: ~/Documents/python_tutorial.

Write this code:

class Robot:
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def introduce_self(self):
        print(f"Hello, my name is {self.name} and my color is {self.color}.")

The __init__ method is a special method called a constructor. It is called when a new object is instantiated, and it’s used to initialize the attributes of the class.

Now, let’s create an object of the Robot class:

r1 = Robot("Addison", "red")
r1.introduce_self()

This creates an instance of Robot named r1 with the name “Addison” and the color “red”. We then call the introduce_self method to make the robot introduce itself.

You should see the output:

1-robot-class

This demonstrates how we’ve created a Robot object and used its method to perform an action.

Using classes and objects in robotics programming allows you to encapsulate behaviors and states associated with specific robotic components or subsystems, making your code more modular, reusable, and easier to manage. For example, each sensor or actuator can be modeled as an object with its methods for starting, stopping, and processing data.

Implementing a Basic Constructor

Let’s learn how to implement a basic constructor in Python, specifically within the context of robotics. 

Constructors are important for initializing robot objects with specific settings or parameters right when they’re created.

In Python, a constructor is defined using the __init__ method of a class. It is automatically invoked when a new object of that class is created.

The __init__ method can take parameters that define the initial state of the object. This is essential for robotics, where each robot might need specific configurations right from the start.

Let’s create a simple class called Robot. This class will have attributes such as name, type, and sensor_count, which we will set using the constructor.

Create a program called robot_constructor.py inside the following folder: ~/Documents/python_tutorial.

Write this code:

class Robot:
    def __init__(self, name, type, sensor_count):
        self.name = name
        self.type = type
        self.sensor_count = sensor_count
        print(f"Robot created: {self.name}, a {self.type} robot with {self.sensor_count} sensors.")

Here, the __init__ method initializes each new Robot instance with a name, type, and sensor count. These attributes allow us to differentiate between various robots, catering to different roles and functionalities in a robotics lab or factory.

Now, let’s create instances of our Robot class to see the constructor in action:

r1 = Robot("Atlas", "Humanoid", 5)
r2 = Robot("Spot", "Quadruped", 4)

This code creates two robots: “Atlas,” a humanoid robot with 5 sensors, and “Spot,” a quadruped robot with 4 sensors.

Now run this script.

2-robot-constructor

You should see output indicating that the robots have been successfully created with their respective attributes. This output verifies that our constructor is working as expected, initializing each robot with its specific characteristics.

Overriding a Function

Let’s explore the concept of overriding functions in Python, particularly in the context of object-oriented programming. This technique is essential in robotics programming when you need different implementations of the same method in parent and child classes.

Let me explain how overriding works with an example from robotics. Imagine you have a basic robot (parent class) that can move and dock to a charging station. When you want to create a special type of robot (child class) that does these actions differently, that’s where overriding comes in.

In programming, overriding lets you take a behavior that already exists in a parent class (like how the robot moves) and give it a new set of instructions in the child class (like making a cleaning robot move in a specific pattern). It’s like saying “ignore the original instructions and use these new ones instead.”

Before we dive into overriding, you need to understand inheritance, which is how we create new types of robots based on our basic robot design. Just like a cleaning robot inherits all the basic features of the basic robot, a child class inherits all the code from its parent class.

Let’s create a base class called Robot. This class will have a simple method that describes the robot’s operation.

Create a file named function_override.py inside the following folder: ~/Documents/python_tutorial, and write this code:

class Robot:
    def action(self):
        print("Performing a generic action")

Here, our Robot class has one method, action, which prints a generic message about the robot’s activity.

Now, let’s create a subclass (also known as “child class”) called FlyingRobot that inherits from Robot class and overrides the action method to provide more specific behavior:

class FlyingRobot(Robot):
    def action(self):
        print("Flying")

In the FlyingRobot subclass, we redefine the action method. When we call the action method on an instance of FlyingRobot, it will print “Flying”, which is specific to flying robots, instead of the generic action message.

Let’s see this in action. We’ll create instances of both Robot and FlyingRobot and call their action method:

generic_robot = Robot()
generic_robot.action()  # This calls the base class method

flying_robot = FlyingRobot()
flying_robot.action()  # This calls the overridden method in the subclass

Save this script, and run it.

You should see this output:

3-function-overrride

This output shows how the action method behaves differently depending on whether it’s called on an instance of the Robot or the FlyingRobot.

Overriding methods is particularly beneficial in robotics when you deal with different types of robots that might share some functionalities but also have unique behaviors. By using overriding, you can ensure that each robot type performs its tasks appropriately while still inheriting from a common base class.

That’s it for this tutorial on function overriding. Thanks, and I’ll see you in the next tutorial.

Keep building!