Static, Class, and Instance Methods in Python
1. Instance Method
Instance methods are the most common type of methods in Python classes. They take 'self' as the
first parameter and can access or modify object (instance) attributes.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says Woof!"
d = Dog("Tommy")
print(d.speak()) # Output: Tommy says Woof!
2. Class Method
Class methods take 'cls' as the first parameter and are used to access or modify class-level
attributes. They are defined using the @classmethod decorator.
class Dog:
species = "Canine"
@classmethod
def get_species(cls):
return f"All dogs are {cls.species}"
print(Dog.get_species()) # Output: All dogs are Canine
3. Static Method
Static methods do not take 'self' or 'cls' as the first parameter. They behave like regular functions
inside a class and are defined using the @staticmethod decorator.
class Dog:
@staticmethod
def bark_sound():
return "Woof!"
print(Dog.bark_sound()) # Output: Woof!
Summary Table
Here is a summary comparing the different types of methods:
| Method Type | First Arg | Access Instance Data | Access Class Data |
Decorator |
|------------------|-----------|----------------------|-------------------|-----
-------------|
| Instance Method | self | Yes | Yes (via self) | None
| Class Method | cls | No | Yes |
@classmethod |
| Static Method | None | No | No |
@staticmethod |