Lesson 47/48 ยท ๐ Leveling Up
๐ Leveling UpLesson 47/48
Phase 9 ยท Leveling Up30 min
Classes, Modeling the World
Bundle data and behaviour together with class, __init__, and self
How would you approach this? Think first, then expand.
A class is a blueprint for creating objects. An object is an instance of a class, the actual thing built from the blueprint.
Think of a class as a cookie cutter, and objects as the cookies.
Think of a class as a cookie cutter, and objects as the cookies.
Your first classpython
class Dog:
def __init__(self, name, breed):
self.name = name # instance variable
self.breed = breed
def bark(self):
return f"{self.name} says: Woof!"
def describe(self):
return f"{self.name} is a {self.breed}"
# Create instances (objects)
fido = Dog("Fido", "Labrador")
rex = Dog("Rex", "German Shepherd")
print(fido.bark()) # Fido says: Woof!
print(rex.describe()) # Rex is a German Shepherd`self` is a reference to the current instance. Every method gets it as the first parameter automatically. When you call
fido.bark(), Python passes fido as self.A real-world class: Serverpython
class Server:
def __init__(self, ip, role):
self.ip = ip
self.role = role
self.is_healthy = True
self.cpu_usage = 0
def check_health(self):
if self.cpu_usage > 90:
self.is_healthy = False
return f"ALERT: {self.ip} CPU critical ({self.cpu_usage}%)"
return f"{self.ip} OK ({self.cpu_usage}% CPU)"
def set_cpu(self, pct):
self.cpu_usage = pct
web1 = Server("10.0.0.1", "web")
web1.set_cpu(95)
print(web1.check_health()) # ALERT: 10.0.0.1 CPU critical (95%)๐In the Real World...
The Kubernetes Python client uses classes for every resource: Pod, Deployment, Service. boto3 uses classes for EC2Instance, S3Bucket, RDSInstance. Understanding classes lets you use any Python SDK properly.
Practice Exercises
0/2 solvedExercise 1 of 2mediumGuided
โฑ 00:00Build a BankAccount Class
Create a BankAccount class with:-
Expected output:
__init__(self, owner, balance=0)- deposit(self, amount), adds to balance- withdraw(self, amount), subtracts, but print "Insufficient funds" if not enough- get_balance(self), returns current balanceExpected output:
Balance: 150Balance: 100Insufficient fundssolution.py
1 / 2
Exercise 2 of 2easy
โฑ 00:00Inventory Item
Create an InventoryItem class with name, price, quantity. Add a total_value() method.
Expected output:
Expected output:
Widget: 3 x ยฃ9.99 = ยฃ29.97solution.py
2 / 2
Solve all 2 exercises to unlock completion