Static methods


Static methods are methods that are bound to a class rather than its object. They are not dependent on the state of the object. They are not passed any reference to a class or an instance. They are used to perform operations that do not require any information about the class or its instances. They are similar to functions that are defined outside of a class. They are usually used to create utility functions that do not require any information about the class or its instances. They are also useful when we want to group some functions together in a class because they are related to that class.

In RhinoCommons, static methods are frequent and this is why it is important to understand how they work.


How to define static methods


class Beam:
    def __init__(self, length, height, width):
        self.length = length
        self.height = height
        self.width = width

    # this is a NON-static method
    def calculate_volume(self):
        """Calculate the volume of the beam"""
        volume = self.length * self.width * self.height
        return volume

    # this is a static method
    @staticmethod  # this is a decorator needed to define a static method
    def calculate_volume_static(length, height, width):
        """Calculate the volume of the beam"""
        volume = length * width * height
        return volume


How to use static methods


# call the method without instantiating the class
volume = Beam.calculate_volume_static(10, 20, 30)

# call the method from an instance of the class
beam = Beam(10, 20, 30)
volume = beam.calculate_volume()



🛠 Exercise


🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍

Solution:

🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍