1.4.2Python & Scientific Computing

Functions, classes, and modules

3,653 words17 min readdifficulty · medium1 backlinks

Functions: Reusable Logic Blocks

Why Functions Matter in ML/AI

In AI/ML workflows, you'll repeatedly:

  • Preprocess data (normalize, tokenize, augment)
  • Compute metrics (accuracy, F1, loss)
  • Train models with different hyperparameters

Without functions: Copy-paste code everywhere, bugs multiply, changes require editing50 places.

With functions: Write once, call many times, fix bugs in one place.

Figure — Functions, classes, and modules

Classes: Data + Behavior Bundles

Deriving Classes from First Principles

Modules: Organizing Code Across Files

Why Modules? Derivation from Scale

Advanced Concepts: *args, **kwargs, Decorators

Variable-Length Arguments

Recall Explain to a 12-year-old

Imagine you're organizing your school backpack: Functions are like labeled pouches. You have a "pencil pouch" (function) that holds all your pencils. Instead of dumping pencils loose everywhere, you put them in the pouch. When you need a pencil, you know exactly where to look. If you need to replace broken pencils, you only fix the pouch, not search whole backpack.

Classes are like your calculator. It's not just buttons (functions) – it also remembers numbers you typed (data/state). A "Calculator" class has memory slots (attributes) and buttons (methods). Each student has their own calculator with their own stored numbers, but all calculators work the same way.

Modules are like different textbooks. You don't carry all your books everywhere – you take your math textbook to math class, science textbook to science. Each book (module) contains related stuff. Your homework script "imports" from these books: from math_textbook import quadratic_formula.

When building AI, you might have a data_cleaning.py module (textbook) with a remove_duplicates() function (pouch) and a NeuralNetwork class (fancy calculator that remembers weights and can compute predictions).

Connections to Other Topics

  • Python basics - syntax, data types, control flow - Functions use control flow internally
  • NumPy arrays and vectorization - Classes often wrap NumPy arrays as attributes
  • Object-oriented programming in ML - Deep dive into inheritance, polymorphism with ML examples
  • scikit-learn API patterns - sklearn's fit/predict pattern is class-based design
  • Building neural networks from scratch - Classes essential for layer abstractions
  • Data pipelines and preprocessing - Modules organize pipeline stages
  • Software engineering for ML - Testing, documentation, version control of modules

#flashcards/ai-ml

What are the three fundamental code organization units in Python? :: Functions (reusable logic), classes (data + behavior), and modules (files organizing related code).

What is the purpose of the __init__ method in a Python class?
Constructor method that initializes instance attributes when creating an object. Called automatically when you write obj = ClassName(args).

Why should you avoid mutable default arguments in function definitions? :: Mutable defaults (like [] or {}) are created once at function definition time and persist across calls, causing unexpected shared state. Use None and create new object inside function.

What does *args allow in a function signature?
Accepts variable number of positional arguments as a tuple. Enables flexible functions like create_model(100, 50, 10) with any number of layers.
What is the difference between from module import function vs import module?
First imports specific names into current namespace (function()), second imports module itself requiring prefix (module.function()). First is convenient, second avoids name conflicts.
Why do class methods need self as the first parameter?
self refers to the instance calling the method. When you call obj.method(x), Python internally does Class.method(obj, x), passing the instance explicitly.
What does if __name__ == '__main__': do in a module?
Code inside runs only when file is executed directly (python module.py), not when imported. Used for testing and demos without affecting imports.
In a KNN classifier class, why does fit() just store the data?
KNN is a lazy learner – no training computation happens. It memorizes training data and does all work during prediction (computing distances to stored samples).
What is the Scikit-learn API pattern that classes follow?
Estimators have fit(X, y) for training and predict(X) for inference. Convention enables consistent interface across different models.
Why return self from a fit() method?
Enables method chaining like Model().fit(X, y).predict(X_test), a convenience pattern from sklearn API design.

Concept Map

unit of

unit of

unit of

provides

bundles

groups

takes

optionally gives

documented by

applied in

example uses

Code Organization

Functions

Classes

Modules

Reusable Logic

Data plus Behavior

Related Code in Files

Parameters

Return Value

Docstring

ML Workflows

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, jab tum machine learning ka koi project banate ho, toh code bahut jaldi bada aur messy ho jata hai. Agar sab kuch ek hi lambe script mein likhoge toh debugging karna nightmare ban jayega, aur same logic baar-baar copy-paste karoge. Isliye Python humein teen tools deta hai code organize karne ke liye – functions, classes, aur modules. Simple analogy samjho: functions ek recipe hai (ek kaam ko step-by-step karti hai), classes ek appliance hai jismein data aur uspe chalne wale controls dono saath rehte hain, aur modules cabinets hain jo related cheezon ko ek file mein group kar dete hain.

Ab function ka core idea yeh hai ki agar tumhe koi logic – jaise MSE (mean squared error) calculate karna – baar-baar chahiye, toh usse ek naam de do aur inputs ko parameters bana do. Phir jitni baar chahiye utni baar bulaao. Note mein jo step-by-step derivation di hai, wahi asli intuition hai: pehle naive tarika (har baar poora formula likhna) galtiyon se bhara hota hai, phir tum usse ek named block banate ho, phir usmein inputs pass karte ho taaki alag-alag data pe kaam kare, phir docstring add karte ho taaki aage koi (ya khud tum) samajh sake, aur last mein default parameters se ek hi function multiple variations (jaise MSE ya RMSE) handle kar leta hai.

Yeh cheez matter kyun karti hai? Kyunki real ML kaam mein tum data preprocess karte ho, metrics compute karte ho, aur models train karte ho – yeh sab repeatedly hota hai. Functions ka asli faayda yeh hai ki tum ek baar likho, hazaar baar use karo, aur agar koi bug mile toh sirf ek jagah fix karo, na ki 50 jagah. Isse tumhara code clean, reusable, aur team ke saath share karne layak ban jaata hai – jo kisi bhi serious AI-ML developer ki pehli zaroorat hai.

Go deeper — visual, from zero

Test yourself — Python & Scientific Computing

Connections