Since you want the "big picture" of how everything fits together, let's combine the blueprint (Classes) and the philosophy (OOP) into one master topic.
Topic 16: Object-Oriented Programming (OOP) & Classes
In languages like C, you focus on functions (doing things). In Python, you focus on objects (things that have data and can do things). OOP allows you to model real-world entities in your code.
1. The Blueprint: The Class
A Class is a template or blueprint. For example, a "Car" class defines that every car has a color, a brand, and a speed.
2. The Instance: The Object
An Object is a specific car built from that blueprint—like "Arjun’s Red Tesla."
3. Key Components of a Class
__init__(The Constructor): A special method that initializes an object's attributes when it is created.self: A reference to the current instance of the class. It’s how the object talks to itself.Attributes: Variables that belong to the object (e.g.,
color,name).Methods: Functions that belong to the object (e.g.,
drive(),stop()).
class Smartphone:
# Constructor: Runs when a new phone is "born"
def __init__(self, brand, model, battery_level=100):
self.brand = brand # Attribute
self.model = model # Attribute
self.battery = battery_level # Attribute
# Method: A behavior the phone can do
def make_call(self, number):
if self.battery > 5:
print(f"Calling {number} from my {self.model}...")
self.battery -= 5
else:
print("Battery too low!")
# Creating objects (Instances)
my_phone = Smartphone("Apple", "iPhone 15")
your_phone = Smartphone("Samsung", "Galaxy S24", 20)
# Accessing attributes and methods
print(my_phone.brand) # Output: Apple
your_phone.make_call("911") # Output: Calling 911 from my Galaxy S24...