Introduction to Object-Oriented Programming in Python (Classes/Objects)

Python is an object-oriented programming language. Almost everything in Python is an object, which has attributes and methods. Object-oriented programming is a very popular programming paradigm, which is a methodology of program design. In simple terms, it refers to the programmer’s understanding and perception of the program and the way they write code. It is a programming philosophy that is closer to reality.

We know that “a program is a collection of instructions”. To simplify program design, we place relatively independent and frequently reused code into functions, which can be called when needed. If a function’s functionality is too complex and bloated, we can further break it down into multiple sub-functions to reduce system complexity.

In the world of object-oriented programming, data and the functions that operate on the data are a logical whole, which we call objects. Objects can receive messages, and the way to solve problems is to create objects and send various messages to them; through message passing, multiple objects in the program can work together, allowing us to construct complex systems and solve real-world problems.

1. Classes and Objects: The Core Concepts of Object-Oriented Programming

Object-oriented programming: combines a set of data and methods for processing that data into an object, and groups objects with similar behaviors into a class. Through encapsulation, we hide the internal details of objects; through inheritance, we achieve specialization and generalization of classes; and through polymorphism, we implement dynamic dispatch based on object types.

In object-oriented programming, a class is an abstract concept, while an object is a concrete concept. A class is a blueprint or template for objects, while an object is an instance of a class and is an entity that can receive messages. Everything is an object, and objects have attributes and behaviors. Each object is unique, and every object belongs to a certain class.

Class (Class): A blueprint or template that defines the common characteristics and behaviors of a certain type of thing. Object (Object): A specific instance created based on a class.

For example, “Student” is a class, while “Xiao Ming” is a specific object created from the “Student” class.

1. Creating a Class

Format: class ClassName The syntax is similar to that of functions, and all code blocks below should be indented.Functions defined within a class are usually referred to as methods, which represent the behaviors of the object, or the messages that the object can receive. The first parameter of a method is usually self, which represents the object that receives the message.

class Student:    # Initialization method, automatically called when creating an object    def __init__(self, name, age, grade):        self.name = name    # Attribute: Name        self.age = age      # Attribute: Age          self.grade = grade  # Attribute: Grade
    # Method: Self-introduction    def introduce(self):        print(f"My name is {self.name}, I am {self.age} years old, and I am in {self.grade}.")
    # Method: Study    def study(self, subject):        print(f"{self.name} is studying {subject}.")

When we call the constructor of the Student class to create an object, memory space needed to store the student object is first allocated in memory, and then the __init__ method is automatically executed to initialize the memory, which means placing data into the memory space. Therefore, we can specify attributes for the student object by adding the __init__ method to the Student class, while also assigning initial values to those attributes. For this reason, the __init__ method is often referred to as the initialization method.

2. Creating Objects Using Classes

# Creating student objectsstudent1 = Student("Xiao Ming", 18, "Senior 3")student2 = Student("Xiao Hong", 17, "Senior 2")
# Calling methods of the objectsstudent1.introduce()  # Output: My name is Xiao Ming, I am 18 years old, and I am in Senior 3.student2.introduce()  # Output: My name is Xiao Hong, I am 17 years old, and I am in Senior 2.
student1.study("Mathematics")  # Output: Xiao Ming is studying Mathematics.

2. The Four Major Features of Object-Oriented Programming

1. Encapsulation: Hides all implementation details that can be hidden, exposing only simple and necessary interfaces to the outside world.

For example, if I want to control a robot to pour me a glass of water, without using object-oriented programming and without any encapsulation, I would need to send a series of instructions to the robot, such as standing up, turning left, walking forward 5 steps, picking up the water cup in front of me, turning around, walking forward 10 steps, bending down, putting down the cup, pressing the water button, waiting 10 seconds, releasing the water button, picking up the cup, turning right, walking forward 5 steps, and putting down the cup, just to complete this simple operation. It sounds cumbersome. According to the philosophy of object-oriented programming, we can encapsulate the action of pouring water into a method of the robot, so when we need the robot to pour water for us, we only need to send a message to the robot object to pour water.

class BankAccount:    def __init__(self, account_holder, balance=0):        self.account_holder = account_holder        self.__balance = balance  # Private attribute, cannot be accessed directly from outside
    # Public method to access private attribute    def deposit(self, amount):        if amount > 0:            self.__balance += amount            print(f"Deposit successful, current balance: {self.__balance}")        else:            print("Deposit amount must be greater than 0.")
    def withdraw(self, amount):        if 0 < amount <= self.__balance:            self.__balance -= amount            print(f"Withdrawal successful, current balance: {self.__balance}")        else:            print("Invalid withdrawal amount.")
    def get_balance(self):        return self.__balance
# Using encapsulationaccount = BankAccount("Zhang San", 1000)account.deposit(500)    # Deposit successful, current balance: 1500account.withdraw(200)   # Withdrawal successful, current balance: 1300print(account.get_balance())  # 1300
# Cannot directly access private attribute# print(account.__balance)  # This will raise an error

2. Inheritance: Subclasses can inherit the attributes and methods of their parent class, achieving code reuse.

# Parent classclass Person:    def __init__(self, name, age):        self.name = name        self.age = age
    def speak(self):        print(f"{self.name} is speaking.")
# Subclass inherits from parent classclass Teacher(Person):    def __init__(self, name, age, subject):        super().__init__(name, age)  # Call the parent class's initialization method        self.subject = subject
    # Method unique to the subclass    def teach(self):        print(f"{self.name} teacher is teaching {self.subject}.")
    # Override the parent class's method    def speak(self):        print(f"{self.name} teacher is giving a lecture.")
class Student(Person):    def __init__(self, name, age, grade):        super().__init__(name, age)        self.grade = grade
    def study(self):        print(f"{self.name} is studying.")
# Using inheritanceteacher = Teacher("Li Teacher", 35, "Mathematics")student = Student("Xiao Wang", 16, "Senior 1")
teacher.speak()  # Li Teacher is giving a lecture.student.speak()  # Xiao Wang is speaking.teacher.teach()  # Li Teacher is teaching Mathematics.

3. Polymorphism: Different objects respond differently to the same method.

class Animal:    def speak(self):        pass
class Dog(Animal):    def speak(self):        return "Woof Woof!"
class Cat(Animal):    def speak(self):        return "Meow Meow!"
class Duck(Animal):    def speak(self):        return "Quack Quack!"
# Demonstration of polymorphismdef animal_sound(animal):    print(animal.speak())
# Same method, different responsesdog = Dog()cat = Cat()duck = Duck()
animal_sound(dog)   # Woof Woof!animal_sound(cat)   # Meow Meow!animal_sound(duck)  # Quack Quack!

4. Abstraction: Python implements abstraction through Abstract Base Classes (ABC).

from abc import ABC, abstractmethod
# Abstract classclass Shape(ABC):    @abstractmethod    def area(self):        pass
    @abstractmethod    def perimeter(self):        pass
# Concrete classes implementing abstract methodsclass Rectangle(Shape):    def __init__(self, width, height):        self.width = width        self.height = height
    def area(self):        return self.width * self.height
    def perimeter(self):        return 2 * (self.width + self.height)
class Circle(Shape):    def __init__(self, radius):        self.radius = radius
    def area(self):        return 3.14 * self.radius ** 2
    def perimeter(self):        return 2 * 3.14 * self.radius
# Usagerect = Rectangle(5, 3)circle = Circle(4)print(f"Rectangle area: {rect.area()}")       # Rectangle area: 15print(f"Circle perimeter: {circle.perimeter()}") # Circle perimeter: 25.12

Object-Oriented Example: Digital Clock

import time
# Define Clock classclass Clock:    """Digital Clock"""
    def __init__(self, hour=0, minute=0, second=0):        """Initialization method        hour: Hour        minute: Minute        second: Second        """        self.hour = hour        self.min = minute        self.sec = second
    def run(self):        """Tick"""        self.sec += 1        if self.sec == 60:            self.sec = 0            self.min += 1            if self.min == 60:                self.min = 0                self.hour += 1                if self.hour == 24:                    self.hour = 0
    def show(self):        """Display time"""        return f'{self.hour:0>2d}:{self.min:0>2d}:{self.sec:0>2d}'

# Create clock objectclock = Clock(23, 59, 58)while True:    # Send message to clock object to read time    print(clock.show())    # Sleep for 1 second    time.sleep(1)    # Send message to clock object to tick    clock.run()

In summary, object-oriented programming is essentially a three-step process. The first step is to define a class, the second step is to create an object, and the third step is to send messages to the object. Object-oriented programming is a very important programming paradigm in Python. Through the concepts of classes and objects, encapsulation, inheritance, and polymorphism, we can build more modular, reusable, and maintainable code.

Leave a Comment