Python Essentials for AI Engineer

Course Content

Python Essentials for AI Engineer

6 sections · 48 lessons

What is a Class?


What you need to know

Class and instances

Python
class Model:    task = "classification"                 # class attribute: shared    def __init__(self, name):        self.name = name                    # instance attribute: per object    def predict(self, x):        return f"{self.name} scored {x}"a = Model("bert-base")b = Model("distilbert")print(a.predict(0.9))          # bert-base scored 0.9print(a.name, b.name)          # bert-base distilbertprint(a.task, b.task)          # classification classificationprint(type(a).__name__)        # Modelprint(vars(a))                 # {'name': 'bert-base'} -> only instance data lives here

vars(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:

Python
from dataclasses import dataclass@dataclassclass Transaction:    txn_id: str    amount: float    merchant: str = "unknown"    def is_high_value(self, limit=10_000):        return self.amount >= limitt = Transaction("T1", 12_500.0, "IRCTC")print(t)                          # Transaction(txn_id='T1', amount=12500.0, merchant='IRCTC')print(t.is_high_value())          # Trueprint(t == Transaction("T1", 12_500.0, "IRCTC"))   # True -> __eq__ compares fields

A 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:

Python
import csv, io# uses the Transaction dataclass defined abovedata = io.StringIO("txn_id,amount,merchant\nT1,499,Swiggy\nT2,15200,IRCTC\nT3,89,Zomato\n")txns = [Transaction(r["txn_id"], float(r["amount"]), r["merchant"]) for r in csv.DictReader(data)]flagged = [t.txn_id for t in txns if t.is_high_value()]print(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 @dataclass generate?" — __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.