Methods


As seen in the definition, a method is a function that is defined inside a class. It is used to define the behaviors of an object. Methods are accessed using the same dot syntax as attributes. The only difference is that we need to add parentheses to the end of the method name. We can also pass arguments to methods just like we do with functions.

In summary, methods are a fundamental part of object-oriented programming and they provide a way to define behaviors or actions that an object can perform with its data.

How to define methods


Here’s an example of a particular method that cuts a beam at a given length:

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

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

    def cut(self, cut_length):
        """
            Cut the beam at a given length.
            The method checks if the beam is long enough to be cut.

            :param cut_length: length at which the beam should be cut
        """
        # get the current length of the beam and substract the cut length
        current_length = self.length
        current_length = current_length - cut_length

        # check if the beam is too short to be cut
        if current_length < 0:
            print("The beam is too short to be cut")
            return False
        else:
            self.length = current_length
            print("The beam has been cut")
            return True


How to use methods


Here’s how we can use the defined method cut() after we created an instance of the Beam class:

# Create an instance of the Beam class
my_beam = Beam(10, 0.2, 0.2)

# test some cuts
my_beam.cut(1)
my_beam.cut(1)
my_beam.cut(10) # <-- this one will fail!



🛠 Exercise


01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍

Solution:

01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍