Object-oriented programming (OOP) organizes code around classes and objects. A class groups functions and data; an object is an instance of that class. Methods are functions defined in classes, while instance variables are attributes attached to a particular object. A car offers a simple analogy: make, model, and color are attributes, while driving and parking are functions. section 4.0 section 4.4
For data science work, OOP helps turn convoluted notebook code into a more structured, flexible, and portable codebase. That can make feature-engineering and model-input processes easier to integrate with other code, support collaboration, and prepare code for production. It is one software engineering practice alongside source control, scaling, exception handling, and automated testing. section 4.0 section 1.5 section 1.0
Think in terms of these building blocks:
- A class is a collection of functions and attributes (data). section 4.0
- An object is a specific instance of a class; the integer 10, for example, is an instance of the integer class. section 4.4
- Instance variables hold values for one object and may differ between objects created from the same class. section 4.4
- Encapsulation means objects are self-contained and can control access to their functions or attributes. section 4.0
A random forest as an object
Python libraries already use OOP extensively. Importing RandomForestClassifier provides a class; creating forest_model makes an object with values such as n_estimators, max_depth, max_features, and random_state. Its methods can train the model, and dot notation reads an attached attribute such as forest_model.max_features. section 4.1.1
Listing 4.2 This code creates a RandomForestClassifier object and specifies several key parameters, including the number of trees (n_estimators = 100) and max_depth.
from sklearn.ensemble import RandomForestClassifier #1
forest_model = RandomForestClassifier( #2
n_estimators = 100, #2
max_depth = 4, #2
max_features = "sqrt", #2
random_state = 0) #2
This listing shows an object being created from RandomForestClassifier while supplying its initial attribute values. section 4.1.1
Because Python is full of objects, OOP is often already present in everyday work with integers, pandas, and scikit-learn. The practical next step is to recognize classes, objects, methods, and instance variables in library code, then use the same structure when building code that must remain understandable and reusable. section 4.1.1 section 4.0












