Quick MCQ โ choose the best answerยถ
A)
@classmethodmethods receiveselfand are used per-objectB)
@classmethodmethods receiveclsand are useful for factoriesC)
@staticmethodalways changes instance state and should accessself
Correct: B โ
@classmethodreceivesclsand is ideal for factories.
Short Exercises (Pyodide-ready)ยถ
Use
User.from_stringto createu3from'Bob:7500'and print whetheru3is VIP (spend >=vip_threshold).Add a
to_dict()instance method toUserthat returns a small dict of{"name":..., "spend":...}and test it.Create a
Utilsclass with a@staticmethod parse_currency(s)that strips$and commas and returns an int.
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.