Back to all posts

Static Methods and Class Methods in Python

🧠 First, the Basics: In Python, there are 3 main types of methods inside a class: Instance Method → Works with object (instance) Class Method → Works with…

🧠 First, the Basics:

In Python, there are 3 main types of methods inside a class:

  1. Instance Method → Works with object (instance)
  2. Class Method → Works with class
  3. Static Method → Doesn't care about class or object

✅ 1. Instance Method (Normal method)

  • Takes self as the first argument.
  • Can access and modify object (instance) data.
Python
class Dog:
    def __init__(self, name):
        self.name = name

    def speak(self):
        print(f"My name is {self.name}")

➤ How to use:

Bash
d = Dog("Bruno")
d.speak()   # Output: My name is Bruno

✅ 2. Class Method

  • Takes cls as the first argument.
  • Can access and modify class-level data.
  • Use @classmethod decorator.
Python
class Dog:
    species = "Canine"  # Class variable
 
    @classmethod
    def get_species(cls):
        print(f"We are {cls.species}")

    @classmethod
    def set_species(cls, species):
        cls.species = species


    def get(self):
        print(f"This is a {self.species} dog.")


# Example usage
dog = Dog()
dog.get()  # Output: This is a Canine dog.
Dog.get_species()  # Output: We are Canine
dog.set_species("Canis familiaris")
dog.get()  # Output: This is a Canis familiaris dog.
Dog.get_species()  # Output: We are Canis familiaris

✅ 3. Static Method

  • Takes no special first argument (no self, no cls)
  • Cannot access object or class data.
  • Use @staticmethod decorator.
  • Used for utility/helper functions.
Python
class Math:
    @staticmethod
    def add(a, b):
        return a + b
    
    def sum(self, a, b):
        return a+b
    

# Example usage
m= Math()
print(m.sum(5, 3))  # Output: 8 
print(m.add(5, 3))  # Output: 8

Keep building your data skillset

Explore more SQL, Python, analytics, and engineering tutorials.