Python Class Methods and Static Methods

PythonPythonBeginner
Practice Now

Introduction

In a galaxy dominated by the Hegemony Planet Empire, the realms of the empire flourish under the watchful eyes of the Imperial Territory Guardians. These guardians are responsible for maintaining order and ensuring that the empire's decreed protocols are upheld. Recently, the guardians have been tasked with deploying and managing a network of stealth drones to monitor the imperial borders.

As a team of coders drafted by the Imperial Tech Division, your objective is to design the software that governs the drone fleet. The key focus of this lab is to utilize Python's class methods and static methods to create a control system that is both efficient and modular. Your software will ensure that the guardians can easily manipulate the drone behaviors and analyze data collected across various sectors without duplicating code.

Are you ready to fulfill your duty to the empire and exhibit your allegiance through lines of code? Let's begin.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ObjectOrientedProgrammingGroup(["`Object-Oriented Programming`"]) python/ObjectOrientedProgrammingGroup -.-> python/class_static_methods("`Class Methods and Static Methods`") subgraph Lab Skills python/class_static_methods -.-> lab-271527{{"`Python Class Methods and Static Methods`"}} end

Setting Up the Drone Class

In this step, you will create the foundational Drone class that all drones will inherit from. This class will have both class methods and static methods which will handle the initialization and global management aspects of the drone fleet.

To start, please open a new Python file named drone.py in the ~/project directory. Place the following code inside:

class Drone:
    fleet_count = 0

    def __init__(self, designation):
        self.designation = designation
        Drone.fleet_count += 1

    @classmethod
    def from_serial_number(cls, serial_number):
        designation = f"Drone-{serial_number}"
        return cls(designation)

    @staticmethod
    def is_valid_designation(designation):
        return designation.startswith("Drone-")

if __name__ == "__main__":
    ## Example usage
    standard_drone = Drone.from_serial_number("SN123")
    print(f"Designation: {standard_drone.designation}")
    print(f"Is valid designation: {Drone.is_valid_designation(standard_drone.designation)}")
    print(f"Fleet count: {Drone.fleet_count}")

This code sets up a Drone class with an initializer, a class method from_serial_number that creates a new drone instance with a proper designation using a serial number, and a static method is_valid_designation that checks if a given designation is valid for a drone.

Use the following command to run your drone.py file and see the example usage in action:

python ~/project/drone.py

You should see output that corresponds to the example usage code within the __main__ block of drone.py:

Designation: Drone-SN123
Is valid designation: True
Fleet count: 1

Implementing Mission Specific Behavior

Now, you will add a mission-related static method to organize the drones based on their designated zones. Create a new method inside the Drone class called assign_zone that assigns a drone to one of the empire's security zones based on the last digit of its serial number.

Modify the existing drone.py file to include the new assign_zone method:

class Drone:
    fleet_count = 0

    def __init__(self, designation):
        self.designation = designation
        Drone.fleet_count += 1

    @classmethod
    def from_serial_number(cls, serial_number):
        designation = f"Drone-{serial_number}"
        return cls(designation)

    @staticmethod
    def is_valid_designation(designation):
        return designation.startswith("Drone-")

    @staticmethod
    def assign_zone(serial_number):
        zone_mapping = {
            "1": "Residential",
            "2": "Commercial",
            "3": "Industrial",
            "4": "Agricultural"
        }
        return zone_mapping.get(serial_number[-1], "Undefined")


if __name__ == "__main__":
    standard_drone = Drone.from_serial_number("SN123")
    print(f"Assigned Zone: {Drone.assign_zone(standard_drone.designation)}")

Run the updated drone.py as before to see the new behavior:

python ~/project/drone.py

The information below should be displayed on your terminal:

Assigned Zone: Industrial

Summary

In this lab, you explored how class methods and static methods can be employed within a Python class to create a modular and efficient control system. By designing a Drone class and practicing the use of class-level functionality, you've learned how to encapsulate both instantiation logic and utility functions that are independent of class instances.

Through this hands-on experience, your skills in object-oriented programming have been sharpened, and you are now more equipped to write clean, reusable code. Hopefully, you feel prepared to defend the Hegemony Planet Empire's territories with your Python prowess. Remember, the power of the empire is only as strong as the code created by its loyal developers!

Other Python Tutorials you may like