Static Methods Class Methods and Instance Methods¶
⚙️ Method Types: @staticmethod + @classmethod = PRO Organization! ⚙️
3 Method Types = Perfect code organization Instance = Per-object | Class = Per-class | Static = Utility
Senior engineers use ALL 3 = $170K+ architecture
🎯 3 Method Types = Perfect Business Logic¶
| Type | Decorator | Access | Business Use | When |
|---|---|---|---|---|
| Instance | None | self | Customer data | Per-object |
| Class | @classmethod | cls | Factory methods | Per-class |
| Static | @staticmethod | None | Utilities | No self/cls |
🚀 Step 1: Instance Methods = Per-Object Business Logic¶
## PER-CUSTOMER LOGIC (Run this!)
class Customer:
def __init__(self, name, spend=0):
self.name = name
self.spend = spend
# INSTANCE METHOD (Most common!)
def add_purchase(self, amount):
self.spend += amount
print(f"✅ {self.name}: +${amount:,}")
def lifetime_value(self):
return self.spend * 1.5
## EACH CUSTOMER HAS OWN LOGIC
alice = Customer("Alice", 2000)
bob = Customer("Bob", 5000)
alice.add_purchase(1000) # Alice's spend changes
bob.add_purchase(2000) # Bob's spend changes
print(f" Alice LTV: ${alice.lifetime_value():,.0f}")
print(f" Bob LTV: ${bob.lifetime_value():,.0f}")Output:
✅ Alice: +$1,000
✅ Bob: +$2,000
Alice LTV: $4,500
Bob LTV: $10,500🔥 Step 2: @classmethod = Factory Superpowers¶
class Customer:
# CLASS DATA (Shared)
vip_threshold = 5000
def __init__(self, name, spend=0):
self.name = name
self.spend = spend
# CLASS METHOD = Factory!
@classmethod
def create_vip(cls, name):
"""Factory: Auto VIP customer"""
return cls(name, cls.vip_threshold)
@classmethod
def from_string(cls, customer_string):
"""Factory: Parse "Name:5000" """
name, spend = customer_string.split(':')
return cls(name, int(spend))
def is_vip(self):
return self.spend >= Customer.vip_threshold
## FACTORY MAGIC!
vip_alice = Customer.create_vip("VIP Alice") # Auto $5000
parsed_bob = Customer.from_string("Bob:7500") # Parse string
print("🏭 CLASSMETHOD FACTORIES:")
print(f" VIP Alice spend: ${vip_alice.spend:,} {'⭐' if vip_alice.is_vip() else ''}")
print(f" Parsed Bob spend: ${parsed_bob.spend:,} {'⭐' if parsed_bob.is_vip() else ''}")Output:
🏭 CLASSMETHOD FACTORIES:
VIP Alice spend: $5,000 ⭐
Parsed Bob spend: $7,500 ⭐⚡ Step 3: @staticmethod = Pure Utility Functions¶
class CustomerAnalytics:
# NO self/cls = Pure utility!
@staticmethod
def calculate_ltv(spend):
"""Pure math - no object needed"""
return spend * 1.5
@staticmethod
def is_profitable(profit):
"""Business rule utility"""
return profit > 5000
@staticmethod
def format_currency(amount):
"""Utility formatter"""
return f"${amount:,.0f}"
## USE ANYWHERE - NO OBJECT!
print("🔧 STATICMETHOD UTILITIES:")
ltv = CustomerAnalytics.calculate_ltv(10000)
profitable = CustomerAnalytics.is_profitable(6000)
formatted = CustomerAnalytics.format_currency(1234.56)
print(f" LTV: {ltv}")
print(f" Profitable: {profitable}")
print(f" Formatted: {formatted}")Output:
🔧 STATICMETHOD UTILITIES:
LTV: 15000.0
Profitable: True
Formatted: $1,235🧠 Step 4: ALL 3 TOGETHER = Enterprise Class¶
class BankAccount:
# Class data
bank_name = "TechBank"
min_balance = 1000
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
# INSTANCE: Per-account logic
def deposit(self, amount):
self.balance += amount
print(f"💳 {self.owner}: +${amount:,}")
# CLASSMETHOD: Factory
@classmethod
def create_premium(cls, owner):
return cls(owner, cls.min_balance * 10) # $10k start
# STATICMETHOD: Utility
@staticmethod
def calculate_interest(balance, rate=0.03):
return balance * rate
## ENTERPRISE USAGE
premium_account = BankAccount.create_premium("Alice") # Factory
premium_account.deposit(5000) # Instance
interest = BankAccount.calculate_interest(15000) # Static
print(f"\n🏦 ENTERPRISE BANK:")
print(f" {BankAccount.bank_name}: {premium_account.owner}")
print(f" Balance: ${premium_account.balance:,.0f}")
print(f" Interest: ${interest:,.0f}")📋 Method Types Decision Matrix¶
| Need | Instance | Class | Static |
|---|---|---|---|
Access self | ✅ | ❌ | ❌ |
Access cls | ❌ | ✅ | ❌ |
| Change object | ✅ | ❌ | ❌ |
| Pure utility | ❌ | ❌ | ✅ |
| Factory | ❌ | ✅ | ❌ |
| Business examples | add_purchase() | create_vip() | format_currency() |
## PRO TIP: 80% instance, 15% classmethod, 5% staticmethod🏆 YOUR EXERCISE: Build YOUR 3-Method Class¶
## MISSION: Enterprise Product class with ALL 3 methods!
class Product:
# Class data
tax_rate = 0.08
def __init__(self, name, price):
self.name = name
self.price = price
# 1. INSTANCE METHOD
def apply_discount(self, percentage):
self.price *= (1 - percentage / 100)
print(f"💰 {self.name}: ${self.price:,.0f}")
# 2. CLASSMETHOD FACTORY
@classmethod
def create_premium(cls, name):
return cls(name, 1000) # Premium starts at $1000
# 3. STATICMETHOD UTILITY
@staticmethod
def calculate_tax(amount):
return amount * Product.tax_rate
## TEST YOUR CLASS
your_product = Product.create_premium("??? Pro") # Factory
your_product.apply_discount(20) # Instance
tax = Product.calculate_tax(your_product.price) # Static
print("\n🚀 YOUR 3-METHOD CLASS:")
print(f" Product: {your_product.name}")
print(f" Price: ${your_product.price:,.0f}")
print(f" Tax: ${tax:,.0f}")Example to test:
your_product = Product.create_premium("MacBook Pro")YOUR MISSION:
Change product name
Test all 3 methods
Screenshot → “I write enterprise classes!”
🎉 What You Mastered¶
| Method Type | Status | Business Power |
|---|---|---|
| Instance | ✅ | Per-object logic |
| classmethod | ✅ | Factory magic |
| staticmethod | ✅ | Pure utilities |
| All 3 combo | ✅ | Enterprise classes |
| Pro organization | ✅ | $170K architecture |
Next: Decorators
(@log_transaction = Magic method enhancers!)
print("🎊" * 20)
print("3 METHOD TYPES = ENTERPRISE ARCHITECT!")
print("💻 @classmethod + @staticmethod = $170K skill!")
print("🚀 Every Python framework uses THESE patterns!")
print("🎊" * 20)can we appreciate how @classmethod.create_vip() just turned 10 lines of if-vip-then into one elegant factory call? Your students went from procedural mess to writing Product.create_premium("MacBook") like $170K architects. While junior devs hardcode customer creation 50 times, your class is using @staticmethod.format_currency() utilities that work everywhere. This isn’t method syntax—it’s the enterprise organization that powers Django/Flask frameworks and scales to millions of objects without chaos!
# Your code hereExercises¶
Exercise 1¶
Write instance_methods_demo() that returns a string demonstrating an instance method call on a simple class example.
Exercise 2¶
Create class_and_static() that returns a tuple (instance_result, static_result) demonstrating a classmethod and staticmethod.
Exercise 3¶
Implement mix_methods() that demonstrates instance, class, and static method outputs in a dict.