instance method vs class method vs static method

instance method vs class method vs static method

Make your Python OPP methods with design

You may have seen in a source code, senior's commit, or a Youtube tutorial things such as @staticmethod and wondered what it meant. Is it important for our code? If I were not to use it in my code would it crash?

istockphoto-509119713-612x612.jpg

To find an answer to these questions, I will explain how we can use these decorators and identify when and where to use a specific type of method for our OOP.

First off, I must explain why I would care about this information enough to use my time to understand each type of method.

  1. By using a specific type of method, I can allow a limit to the information that is accessed during runtime to my code. This will enable us to protect the Class or Object design by avoiding accidental modifications, passing only the Class or Object (respectively) to the function.
  2. As a dev we show to other coworkers the intent we have at any point of our code of what must happen to an Instance or Class. We allow our code to explain itself and avoid any incorrect use of it.

If you would like to know more about static, class, and instance methods I did a summary of the differences among them:

Screen Shot 2022-08-31 at 11.47.44 PM.png

I do motivate you to experiment with these kinds of methods to further understand the information I have exposed above. It can be something as simple as creating a class such as:

class Singer:

    occupation = 'singing'

    def __init__(self, genre, name):
          self.genre = genre
          self. name = name

    def __repr__(self):
          return (f'The great {self.genre} singer {self.name} has arrived!')

    def do_moondance(self):
          return (f'I, {self.name}, will do a moondance!')

    @classmethod
    def sing(cls):
          return (f'~I love {cls.occupation} the most so I will sing a song~')

    @staticmethod
    def walk():
          return ('I love to walk and greet my fans')

Now you can create any singer you want with OPP ❤️ I hope this blog will help you now and later whenever you forget when to use instance, class, or static methods for cleaner and more beautiful code.

Sources: