Course Content
Python Essentials for AI Engineer
6 sections · 48 lessons
What is a Class?
What you need to know
Class and instances
1class Model:2 task = "classification" # class attribute: shared34 def __init__(self, name):5 self.name = name # instance attribute: per object67 def predict(self, x):8 return f"{self.name} scored {x}"910a = Model("bert-base")11b = Model("distilbert")12print(a.predict(0.9)) # bert-base scored 0.913print(a.name, b.name) # bert-base distilbert14print(a.task, b.task) # classification classification15print(type(a).__name__) # Model16print(vars(a)) # {'name': 'bert-base'} -> only instance data lives herevars(a) (the same as a.__dict__) shows that the instance stores only its own attributes. The method predict and the class attribute task live once, on the class, and every instance finds them there.
Classes are objects too
Model itself is an object (its type is type). You can pass a class to a function, store it in a dict, and call it later — a common way to choose a model class from a config string.
Dataclasses for data-holding classes
Writing __init__, __repr__ and __eq__ by hand for a record is repetitive. @dataclass generates them from type-annotated fields:
1from dataclasses import dataclass23@dataclass4class Transaction:5 txn_id: str6 amount: float7 merchant: str = "unknown"89 def is_high_value(self, limit=10_000):10 return self.amount >= limit1112t = Transaction("T1", 12_500.0, "IRCTC")13print(t) # Transaction(txn_id='T1', amount=12500.0, merchant='IRCTC')14print(t.is_high_value()) # True15print(t == Transaction("T1", 12_500.0, "IRCTC")) # True -> __eq__ compares fieldsA real-life example
A fraud-analysis script reads UPI transactions from a CSV. Version one passes raw dicts around, so every function repeats float(row["amount"]), and a typo like row["ammount"] only fails at runtime deep inside a report. Version two converts each row once into a Transaction object:
1import csv, io2# uses the Transaction dataclass defined above3data = io.StringIO("txn_id,amount,merchant\nT1,499,Swiggy\nT2,15200,IRCTC\nT3,89,Zomato\n")4txns = [Transaction(r["txn_id"], float(r["amount"]), r["merchant"]) for r in csv.DictReader(data)]56flagged = [t.txn_id for t in txns if t.is_high_value()]7print(flagged) # ['T2']Parsing happens in one place, the fields are documented in the class, your editor autocompletes t.amount, and a type checker catches t.ammount. The "high value" rule now lives next to the data it is about.
Follow-up questions to expect
- "What is the difference between a class and an object?" — The class is the definition; an object is an instance created from it. One class, many objects.
- "What does
@dataclassgenerate?" —__init__,__repr__and__eq__by default; with options, ordering methods, immutability (frozen=True) and__slots__(slots=True). - "Where do methods live — on the class or the instance?" — On the class. Instances find them through attribute lookup, which is why one method definition serves every instance.