Complete Guide to Object-Oriented Programming in Python ๐Ÿ

Complete Guide to Object-Oriented Programming in Python ๐Ÿ

Understand class, def, and self from scratch

๐Ÿ“– Introduction

Have you encountered these confusions while learning Python:

  • <span>What is the difference between class and def?</span>
  • <span>What exactly is self? Why do we need to write it?</span>
  • <span>What is the purpose of if __name__ == "__main__"?</span>

1๏ธโƒฃ Basic Concepts: def and class

๐ŸŽฏ Understanding in One Sentence

  • def = defines a functionality (function), representing an independent feature
  • class = defines a template (class), grouping related functionalities together
# def: independent functionality
def cut_fruit(fruit_name):    print(f"Cutting {fruit_name}")
cut_fruit("Apple")
cut_fruit("Banana")
# ==========================================
# class: organizing related functionalities together
class KitchenAssistant:    def cut_fruit(self, fruit_name):        print(f"Cutting {fruit_name}")
    def make_juice(self, fruit_name):        print(f"Juicing {fruit_name}")
    def plate(self):        print("Plating")
assistant = KitchenAssistant()
assistant.cut_fruit("Apple")
assistant.make_juice("Orange")
assistant.plate()

๐Ÿ’ก When to use def and when to use class?

Scenario Usage Example
Simple functionality def Calculating average
Grouping related functionalities class Student management (including name, grades, printing information, etc.)
Need to maintain state class Bank account (needs to remember balance)
One-time operation def Printing logs

2๏ธโƒฃ What is the mysterious self?

๐ŸŽฏ Core Understanding

self = “myself” (the object itself), allowing different objects to be operated on

๐Ÿ“ Detailed Explanation

class Student:    def __init__(self, name, age):        self.name = name  # self represents "this student object"
        self.age = age
    def introduce(self):        print(f"My name is {self.name}, I am {self.age} years old")
# Creating two students
xiaoming = Student("Xiaoming", 18)
xiaohong = Student("Xiaohong", 20)
xiaoming.introduce()  # self = xiaoming
xiaohong.introduce()  # self = xiaohong
```
**Output:**
```My name is Xiaoming, I am 18 years old
My name is Xiaohong, I am 20 years old
class BankAccount:    def __init__(self, owner, balance):        self.owner = owner        self.balance = balance
    def deposit(self, amount):        self.balance += amount  # Modify "my account" balance        print(f"{self.owner}'s account deposited {amount}, balance: {self.balance}")
# Creating two accounts
accountA = BankAccount("Zhang San", 1000)
accountB = BankAccount("Li Si", 500)
accountA.deposit(200)  # self = accountA, only modifies accountA's balance
accountB.deposit(300)  # self = accountB, only modifies accountB's balance
print(f"Zhang San's balance: {accountA.balance}")  # 1200
print(f"Li Si's balance: {accountB.balance}")  # 800

3๏ธโƒฃ Detailed Explanation of if __name__ == “__main__”

๐ŸŽฏ Purpose

Distinguish between “direct execution” and “imported”

๐Ÿ“ Problem Scenario

# File: tools.py
def print_greeting():    print("Hello!")
print("Loading toolbox...")
print_greeting()
# File: main.py
import tools
print("This is the main program")

**Running main.py:**
“`Loading toolbox… โ† ๐Ÿ˜ฑ Not wanted
Hello! โ† ๐Ÿ˜ฑ Not wanted
This is the main program

Problem: The test code is executed when imported!

How to solve this problem, see the code below:

# ========== File: student_manager.py ==========class Student:    """Student class (can be imported)"""
    def __init__(self, name, age):        self.name = name        self.age = age        self.grades = []
    def add_grade(self, grade):        self.grades.append(grade)
    def calculate_average(self):        if not self.grades:            return 0        return sum(self.grades) / len(self.grades)
    def display_info(self):        average = self.calculate_average()        print(f"Name: {self.name}, Age: {self.age}, Average: {average:.1f}")

# Constants (can be imported)
passing_score = 60
excellent_score = 90

# ========== Test Code (will not be imported)==========
if __name__ == "__main__":    print("="*50)    print("๐Ÿงช Student Management System Test")    print("="*50)
    # Test 1: Create student (directly using class)    print("\n[Test 1] Create Student")    student1 = Student("Xiaoming", 18)  # โœ… Directly create using class    print(f"โœ… Created successfully: {student1.name}, {student1.age} years old")
    # Test 2: Add grades    print("\n[Test 2] Add Grades")    student1.add_grade(85)    student1.add_grade(90)    student1.add_grade(78)    print(f"โœ… Grades list: {student1.grades}")
    # Test 3: Calculate average    print("\n[Test 3] Calculate Average")    average = student1.calculate_average()    print(f"โœ… Average: {average:.1f}")
    # Test 4: Display info    print("\n[Test 4] Display Info")    student1.display_info()
    # Test 5: Determine grade    print("\n[Test 5] Determine Grade")    if average >= excellent_score:        print("๐ŸŽ‰ Excellent!")    elif average >= passing_score:        print("๐Ÿ‘ Passed")    else:        print("๐Ÿ˜ข Failed")
    print("\n" + "="*50)    print("โœ… All tests passed!")    print("="*50)

Direct execution yields test results, directly runningresults show the results obtained from the test code after if __name__ == “__main__”::

python student_manager.py

**Output remains unchanged:**
“`==================================================
๐Ÿงช Student Management System Test
==================================================
[Test 1] Create Student
โœ… Created successfully: Xiaoming, 18 years old
[Test 2] Add Grades
โœ… Grades list: [85, 90, 78]
[Test 3] Calculate Average
โœ… Average: 84.3
[Test 4] Display Info
Name: Xiaoming, Age: 18, Average: 84.3
[Test 5] Determine Grade
๐Ÿ‘ Passed
==================================================
โœ… All tests passed!
==================================================

Importing and using student_manager.py, but the results do not show the code after if __name__ == “__main__”: as follows:

# ========== File: main.py ==========import student_manager
print("๐Ÿซ School Management System\n")
# Directly create students (more concise!)
students = [    student_manager.Student("Zhang San", 19),  # โœ… Directly create using class    student_manager.Student("Li Si", 20),    student_manager.Student("Wang Wu", 18)]
# Add grades
students[0].add_grade(95)
students[0].add_grade(88)
students[0].add_grade(92)
students[1].add_grade(78)
students[1].add_grade(82)
students[1].add_grade(75)
students[2].add_grade(92)
students[2].add_grade(96)
students[2].add_grade(88)
# Display info
print("All student information:")
for student in students:    student.display_info()
# Using constants
print(f"\n๐Ÿ“Š Grading Standards:")
print(f"Passing Score: {student_manager.passing_score} points")
print(f"Excellent Score: {student_manager.excellent_score} points")

**Running result (completely identical):**
“`๐Ÿซ School Management System
All student information:
Name: Zhang San, Age: 19, Average: 91.7
Name: Li Si, Age: 20, Average: 78.3
Name: Wang Wu, Age: 18, Average: 92.0
๐Ÿ“Š Grading Standards:
Passing Score: 60 points
Excellent Score: 90 points

Leave a Comment