🧠 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 class
- Static Method → Doesn't care about class or object
✅ 1. Instance Method (Normal method)
- Takes
selfas the first argument. - Can access and modify object (instance) data.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
print(f"My name is {self.name}")
➤ How to use:
d = Dog("Bruno")
d.speak() # Output: My name is Bruno
✅ 2. Class Method
- Takes
clsas the first argument. - Can access and modify class-level data.
- Use
@classmethoddecorator.
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
@staticmethoddecorator. - Used for utility/helper functions.
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