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 |
|
Customer data |
Per-object |
Class |
|
|
Factory methods |
Per-class |
Static |
|
None |
Utilities |
No |
π 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 |
β |
β |
β |
Access |
β |
β |
β |
Change object |
β |
β |
β |
Pure utility |
β |
β |
β |
Factory |
β |
β |
β |
Business examples |
|
|
|
# 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 here