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.

PYTHON
# 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:

PYTHON
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 always self, representing the current object instance.

Example: Defining a Student Class (Difficulty: Star)

PYTHON
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
▶ Try it Yourself

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.

PYTHON
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 self can 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):

PYTHON
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)

PYTHON
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
▶ Try it Yourself

Common Use Cases


FAQ

Q What's the difference between a method and a function?
A A method is a function defined inside a class, with 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.
Q Can self be renamed to something else?
A Technically yes, but never change it. 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.
Q When should I use a class vs. a function?
A If you need to maintain state (data), use a class — like a bank account tracking balance. If you're doing a one-time calculation (input -> process -> output), use a function — like temperature conversion. A simple rule: if you need only 1-2 functions, functions suffice; if multiple related functions share the same data, use a class.

Summary


Exercises

  1. Beginner (Difficulty: Star): Define a Car class with brand, color, and speed attributes. Include an accelerate(value) method to increase speed and a show_speed() method to display the current speed.

  2. Intermediate (Difficulty: Star-Star): Define a Student class. Use a class attribute to track the total number of students, and instance attributes to record each student's name and score. Implement a get_grade() method that returns a letter grade (A, B, C, D).

  3. Advanced (Difficulty: Star-Star-Star): Define a Library class and a Book class. Book has a title, author, and borrowed status. Library has four methods: add_book(book), borrow(title), return_book(title), and show_books().

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏