Classes and Objects
In the last few lessons, we organized code using functions — a "procedural" approach focused on "what to do." Object-Oriented Programming (OOP) focuses on "who does it" — packaging data and the methods that operate on that data into an object. Everything in Python is an object; understanding OOP is a key step forward.
1. What are Classes and Objects
A class is a blueprint; an object is a concrete instance created from that blueprint.
# Define a "Dog" class — the blueprint
class Dog:
pass
# Create specific "Dog" objects from the blueprint
my_dog = Dog()
print(type(my_dog)) # <class '__main__.Dog'>
print(my_dog) # <__main__.Dog object at 0x...>
Just like "dog" as a breed is a concept (class), the specific dog named Wangcai you own is an instance (object). One class can create countless objects.
Tip: Real-world analogy: A class is "blueprint," an object is the "physical thing built from the blueprint." One blueprint can produce many physical things, each with its own state (e.g., different dogs have different names and ages).
2. __init__: The Constructor Method
When creating an object, the __init__ method is automatically called to initialize the object's attributes:
class Dog:
"""Dog class"""
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age
# Pass parameters when creating objects
dog1 = Dog("Wangcai", 3)
dog2 = Dog("Xiaobai", 1)
print(dog1.name) # Wangcai
print(dog2.name) # Xiaobai
print(dog1.age) # 3
Note:
__init__is not the constructor — the object is created before it's called. The actual constructor is__new__, but you almost never need to touch it. The first parameter of__init__is alwaysself, representing the current object instance.
Example: Defining a Student Class (Difficulty: Star)
class Student:
"""Student class"""
def __init__(self, name, student_id, score):
self.name = name
self.student_id = student_id
self.score = score
def introduce(self):
"""Self introduction"""
return f"My name is {self.name}, ID: {self.student_id}, score: {self.score}."
def is_pass(self):
"""Check if passing"""
return self.score >= 60
# Create student objects
s1 = Student("Zhang San", "2024001", 85)
s2 = Student("Li Si", "2024002", 45)
print(s1.introduce()) # My name is Zhang San, ID: 2024001, score: 85.
print(s2.introduce()) # My name is Li Si, ID: 2024002, score: 45.
print(f"Is Zhang San passing? {s1.is_pass()}") # True
print(f"Is Li Si passing? {s2.is_pass()}") # False
3. Methods: Object Behaviors
Functions defined inside a class are called methods. Their first parameter is always self — representing the object itself that calls the method.
class Calculator:
"""Simple calculator"""
def __init__(self):
self.result = 0
def add(self, value):
self.result += value
return self
def subtract(self, value):
self.result -= value
return self
def show(self):
return self.result
calc = Calculator()
calc.add(10)
calc.subtract(3)
print(calc.show()) # 7
# Method chaining — each method returns self
result = Calculator().add(10).subtract(3).add(5).show()
print(result) # 12
Tip: Method chaining trick: Methods that return
selfcan be chained. Many Python libraries (like pandas) use this pattern extensively.
4. Instance Attributes vs. Class Attributes
Attributes can be defined on the instance (unique to each object) or on the class (shared by all objects):
class Student:
# Class attribute — shared by all students
school = "First High School"
total_count = 0
def __init__(self, name):
# Instance attribute — unique to each student
self.name = name
Student.total_count += 1
s1 = Student("Zhang San")
s2 = Student("Li Si")
# Class attributes accessed via the class name
print(Student.school) # First High School
print(Student.total_count) # 2
# Also accessible via instances (if no instance attribute with the same name)
print(s1.school) # First High School
print(s2.school) # First High School
# Modifying a class attribute affects all instances
Student.school = "Second High School"
print(s1.school) # Second High School
Example: Bank Account (Difficulty: Star-Star)
class BankAccount:
"""Bank account"""
bank_name = "Python Bank" # Class attribute
interest_rate = 0.003 # Annual interest rate 0.3%
def __init__(self, owner, balance=0):
self.owner = owner # Instance attribute
self.balance = balance # Instance attribute
def deposit(self, amount):
self.balance += amount
return f"Deposited {amount}, balance: {self.balance}"
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient balance!"
self.balance -= amount
return f"Withdrew {amount}, balance: {self.balance}"
def yearly_interest(self):
"""Calculate yearly interest"""
interest = self.balance * BankAccount.interest_rate
return f"Yearly interest: {interest:.2f}"
acc1 = BankAccount("Zhang San", 10000)
acc2 = BankAccount("Li Si", 5000)
print(acc1.deposit(5000)) # Deposited 5000, balance: 15000
print(acc2.withdraw(2000)) # Withdrew 2000, balance: 3000
print(acc1.yearly_interest()) # Yearly interest: 4.50
# All accounts share the same interest rate
print(acc1.interest_rate) # 0.003
print(acc2.interest_rate) # 0.003
Common Use Cases
- Data modeling: Map real-world entities to code — users, orders, products are all represented by classes.
- State management: Objects hold state (attributes), methods manipulate that state — e.g., game characters, shopping carts.
- Code organization: Related data and functions are packaged together, cleaner than scattered functions.
- Framework extension: Django's models, Flask's application, GUI components are all implemented via classes.
FAQ
self as the first parameter. Functions can exist independently; methods must be called via an object or class. Essentially, methods are functions where Python automatically passes the caller as the first argument.self be renamed to something else?self is a hard rule in the Python community. Changing the name would work, but anyone reading your code (including your future self) would find it strange. Always use self.Summary
- A class is a blueprint; an object is a concrete instance created from it
__init__is the initialization method, automatically called when creating an object- The first parameter of methods is
self, representing the current object - Instance attributes are unique to each object; class attributes are shared by all objects
- Classes package data and the methods that operate on that data together
Exercises
-
Beginner (Difficulty: Star): Define a
Carclass withbrand,color, andspeedattributes. Include anaccelerate(value)method to increase speed and ashow_speed()method to display the current speed. -
Intermediate (Difficulty: Star-Star): Define a
Studentclass. Use a class attribute to track the total number of students, and instance attributes to record each student's name and score. Implement aget_grade()method that returns a letter grade (A, B, C, D). -
Advanced (Difficulty: Star-Star-Star): Define a
Libraryclass and aBookclass.Bookhas a title, author, and borrowed status.Libraryhas four methods:add_book(book),borrow(title),return_book(title), andshow_books().



