Python: Classes and Objects

Last updated: 2026-09-22

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)

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully


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)

▶ Try it Yourself

Output:

TEXT 📖 Display only
# Function defined successfully


5. Common Use Cases

▶ Example: Student Grade Management Class (Difficulty ⭐⭐)

▶ Try it Yourself

Output:

TEXT 📖 Display only
Student: Alice (001)
  Chinese: 85 (Pass)
  Math: 72 (Pass)
  English: 90 (Pass)
  Average: 82.3

Student: Bob (002)
  Chinese: 55 (Fail)
  Math: 48 (Fail)
  Average: 51.5

Total students: 2


5. 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().

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

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

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