Instance Methods
Instance methods are the most common type of method in Python classes. They must be called on a class instance, and their first parameter is always self, which references the specific object instance.
class User:
def __init__(self, name, email):
self.name = name
self.email = email
def display_info(self):
print(f"Name: {self.name}, Email: {self.email}")
# Calling the instance method
user = User("Alice", "alice@example.com")
user.display_info()
Key characteristics:
- Can access and modify instance attributes (
self.name) - Can access class attributes through
self.__class__
Class Methods
Class methods are defined using the @classmethod decorator. The first parameter is cls, which references the class itself. These methods can be called without creating an instance.
class Configuration:
default_timeout = 30
@classmethod
def set_timeout(cls, seconds):
cls.default_timeout = seconds
print(f"Timeout updated to {seconds} seconds")
@classmethod
def get_timeout(cls):
return cls.default_timeout
# Usage
Configuration.set_timeout(60)
timeout = Configuration.get_timeout()
Common use cases:
- Factory patterns for creating different types of class instances
- Managing class-level variables that don't depend on instance state
Static Methods
Static methods use the @staticmethod decorator and do not receive self or cls as parameters. They behave like regular functions but are logically grouped within the class namespace.
class Geometry:
@staticmethod
def rectangle_area(width, height):
return width * height
@staticmethod
def circle_area(radius):
return 3.14159 * radius ** 2
# Usage
area = Geometry.rectangle_area(5, 10)
circle = Geometry.circle_area(7)
Common use cases:
- Utility functions that are conceptually related to the class
- Code organization when functions belong to a specific domain
Quick Reference
| Method Type | Decorator | First Param | Instance Required |
|---|---|---|---|
| Instance | None | self | Yes |
| Class | @classmethod | cls | No |
| Static | @staticmethod | None | No |
Decision Guide
- Instance method: When you need to work with instance-specific data
- Class method: When you need to work with class-level data or create alternative constructors
- Static method: When the function is related to the class but doesn't need access to class or instance data
Complete Example
class Document:
def __init__(self, title, content):
self.title = title
self.content = content
# Instance method
def word_count(self):
return len(self.content.split())
# Class method (factory pattern)
@classmethod
def from_file(cls, filename):
with open(filename, 'r') as f:
lines = f.readlines()
return cls(lines[0].strip(), ''.join(lines[1:]))
# Static method
@staticmethod
def validate_title(title):
return len(title) > 0 and len(title) <= 100
# Usage demonstration
doc = Document("Report", "This is the document content")
print(doc.word_count())
new_doc = Document.from_file("data.txt")
print(Document.validate_title("Valid Title"))