-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10_classes_and_objects.py
More file actions
79 lines (62 loc) · 2.29 KB
/
10_classes_and_objects.py
File metadata and controls
79 lines (62 loc) · 2.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""
Module 10: Classes and Objects
Learn: class, __init__, self, methods
In the advanced courses, you'll use objects constantly:
client = Anthropic()
workflow = StateGraph(AgentState)
response = client.messages.create(model=MODEL, ...)
Understanding classes helps you read SDK code confidently.
"""
# --- Basic class ---
class MenuItem:
def __init__(self, name, price, category="main"):
self.name = name
self.price = price
self.category = category
def describe(self):
return f"{self.name} (${self.price:.2f}) [{self.category}]"
# Create objects (instances)
burger = MenuItem("Mushroom Burger", 12.99)
bowl = MenuItem("Quinoa Power Bowl", 10.99, category="bowl")
print(burger.describe())
print(bowl.describe())
print(f"Burger price: {burger.price}")
# --- __str__ for nice printing ---
class AgentConfig:
def __init__(self, role, model="gpt-4o-mini"):
self.role = role
self.model = model
self.history = []
def __str__(self):
return f"Agent({self.role}, model={self.model})"
def add_message(self, role, content):
self.history.append({"role": role, "content": content})
def message_count(self):
return len(self.history)
agent = AgentConfig("SQL Expert")
print(f"\n{agent}") # Uses __str__
agent.add_message("user", "How many orders?")
agent.add_message("assistant", "Let me check...")
print(f"Messages: {agent.message_count()}")
# --- Why this matters: SDK clients are just objects ---
# In the Claude Code agent:
# client = Anthropic() ← creates an object
# response = client.messages.create(...) ← calls a method
#
# In the RAG workshop:
# client = QdrantClient(":memory:") ← creates an object
# client.add(collection, documents) ← calls a method
# --- @property for computed values ---
class Session:
def __init__(self):
self.events = []
def add_event(self, event):
self.events.append(event)
@property
def event_count(self):
return len(self.events) # No () needed when called
session = Session()
session.add_event("start")
session.add_event("query")
print(f"\nEvents: {session.event_count}") # Looks like an attribute, acts like a method
# 🎯 Exercise: Create a Tool class with name, description, and a run() method