What is Object-Oriented Programming (OOP)?
In OOP, we group data (attributes) and behavior (methods) into "objects". This makes code more modular, reusable, and organized. A class is a blueprint for creating objects.
python
The Anatomy of a Class: __init__ and self
1. __init__ (The Constructor)
This is a special method that is called automatically when you create a new object. It's used to initialize the object's initial data.
2. self (The Object Instance)
Wait! Every method must have
self as the first argument. This represents the specific instance of the class that's currently being worked with.python
Instance vs Class Attributes
Instance Attributes
Created inside
__init__, these belong to a specific object. Every user has their own unique name.Class Attributes
Defined outside all methods, these belong to the class itself and are shared by all its objects.
python
Methods: Instance, Class, and Static
- Instance Methods: Take
selfas the first argument. Accesses and modifies object-level data. - Class Methods: Take
clsas the first argument. Accesses and modifies class-level data. - Static Methods: Take no special arguments. Just regular functions that happen to live inside a class.
python
Encapsulation: Private Attributes?
Python doesn't have true
private or protected keywords. However, we use a single underscore _ to indicate that an attribute is intended for internal use only.python
Pro Tip: Use double underscores__for name mangling to prevent accidental overriding in subclasses.
Summary
| Term | Description |
|---|---|
| Class | The blueprint/template |
| Object | The actual data/"instance" |
| init | The constructor method |
| self | Reference to the current object |
| Attribute | Variable belonging to class/object |
| Method | Function belonging to class/object |
| Encapsulation | Hiding internal details (_attribute) |
| Best For | Modeling real-world objects, managing complex state |
| Class Attribute | Shared across all instances (cls.attribute) |