What is Object-Oriented Programming?¶
Imagine you want to create a simple game like “Pop the Balloon.” Traditional programming might involve writing code like “Check if a balloon is clicked,” then “Move the balloon,” then “Update the score”… These codes are scattered everywhere, like a pile of loose parts. But with an object-oriented approach, you’d treat the “balloon” itself as an independent “character”—it has its own color, size (these are “attributes”), and behaviors like “move” or “disappear when clicked” (these are “methods”). By encapsulating data and behavior within an “object,” it becomes more like how we observe the real world!
Object-Oriented Programming (OOP) centers on “objects,” breaking problems into individual objects. Each object is responsible for its own attributes and behaviors. Python is an OOP-supported language, and understanding classes and objects is the first step into Python’s OOP world.
What is a “Class” in Python?¶
A “Class” is like a blueprint or template describing an object’s shared characteristics and behaviors. For example, “Animal” is a class with common attributes (e.g., being alive, breathing) and behaviors (e.g., running, making sounds). Specific “Cat” or “Dog” are individual “objects” (instances) of this class.
In Python, we define a class using the class keyword. For example, a “Car” class:
class Car:
# Here, we'll define the car's attributes and methods
pass # pass is a placeholder for future content
This Car class is empty. We need to add “attributes” and “methods” to it.
Components of a Class: Attributes and Methods¶
- Attributes: An object’s “characteristics,” like a car’s color, brand, or speed. In Python, these are variables within the class.
- Methods: An object’s “behaviors,” like a car “driving” or “refueling.” In Python, these are functions within the class (note: functions inside a class are called “methods,” not regular functions).
1. Defining Attributes¶
To add attributes to the Car class (e.g., color, speed), we use the constructor method __init__ (a special Python method that runs automatically when an object is created).
class Car:
# Constructor: Initializes object attributes
def __init__(self, color, brand):
# self is a special parameter pointing to the object itself (e.g., this car)
self.color = color # Instance attribute: color
self.brand = brand # Instance attribute: brand
self.speed = 0 # Initial speed is 0
- The first parameter of
__init__must beself, which refers to the current object (e.g., “this car”). - When creating an object,
__init__runs automatically, and parameters (e.g.,colorandbrand) are assigned toself’s attributes.
2. Defining Methods¶
Add “behaviors” to the Car class, such as drive (accelerate) and stop (decelerate):
class Car:
def __init__(self, color, brand):
self.color = color
self.brand = brand
self.speed = 0
# Drive method: Accelerate
def drive(self, speed_increase):
self.speed += speed_increase
print(f"{self.brand}'s {self.color} car is accelerating. Current speed: {self.speed}")
# Stop method: Decelerate to 0
def stop(self):
self.speed = 0
print(f"{self.brand}'s {self.color} car has stopped. Speed: {self.speed}")
Here, drive and stop are methods of the Car class, accessible by any object (instance).
From Class to Object: Instantiation¶
With a class, we create specific objects (instantiation), like building real cars from a blueprint.
# Create an object: Call the class name() and pass constructor parameters
my_car = Car("Red", "Tesla") # Instantiate a Car object with red color and Tesla brand
# Access attributes: object.attribute_name
print(my_car.color) # Output: Red
print(my_car.brand) # Output: Tesla
# Call methods: object.method_name()
my_car.drive(50) # Output: Tesla's Red car is accelerating. Current speed: 50
my_car.drive(30) # Output: Tesla's Red car is accelerating. Current speed: 80
my_car.stop() # Output: Tesla's Red car has stopped. Speed: 0
Key Point: Each object (e.g., my_car) has independent attributes. Modifying one object’s attributes won’t affect others.
Why is self Needed?¶
self is a Python “convention” parameter that tells methods “which object to operate on.” For example, in my_car.drive(50), self automatically points to my_car, so self.speed refers to my_car’s speed attribute. Without self, methods can’t distinguish which object’s attributes to use, causing errors.
Practice Exercise: Define a “Student” Class¶
Try writing a simple Student class with:
- Attributes: name (name), age (age), score (score)
- Methods: study() (increases score by 10), introduce() (prints name, age, score)
class Student:
def __init__(self, name, age, score=0): # score defaults to 0
self.name = name
self.age = age
self.score = score
def study(self):
self.score += 10
print(f"{self.name} studies. Score becomes: {self.score}")
def introduce(self):
print(f"I'm {self.name}, {self.age} years old, score: {self.score}")
# Create a student object
student1 = Student("Xiaoming", 15, 80)
student1.introduce() # Output: I'm Xiaoming, 15 years old, score: 80
student1.study() # Output: Xiaoming studies. Score becomes: 90
student1.introduce() # Output: I'm Xiaoming, 15 years old, score: 90
Summary¶
- Class: A blueprint for objects, defining attributes and methods.
- Object: An instance of a class, a concrete “thing” with its own attribute values.
- Attributes: Object characteristics (variables).
- Methods: Object behaviors (functions within the class).
__init__: The constructor method, auto-runs when an object is created to initialize attributes.self: A special parameter pointing to the current object (first parameter of all methods).
The core idea of OOP is “encapsulation”—grouping data and methods to operate on it, making code more modular and maintainable. We’ll explore more concepts (like inheritance, polymorphism) later, but first, master the basics of classes and objects!