I. What Is Object-Oriented Programming
Object-Oriented Programming (OOP) is a programming approach that organizes programs around objects.
In object-oriented programming, a program is no longer composed merely of a set of independent functions and data; instead, related data and operations are encapsulated into objects, and business functionality is completed through collaboration among objects.
For example, an e-commerce system might include:
- User object: stores user information and handles user-related operations.
- Product object: stores product information and manages product attributes.
- Order object: stores order data and handles order status.
- Payment object: handles payment requests and payment results.
These objects each assume different responsibilities and complete business processes by calling each other's methods.
1. Object-Oriented vs. Procedural
Procedural programming focuses more on the steps of program execution and breaks a problem down into a series of functions and operations.
Object-oriented programming focuses more on the objects involved in the business, as well as the data and behavior that the objects possess.
Take a bank account as an example.
Procedural implementation:
balance = 1000
def deposit(balance, amount):
return balance + amount
def withdraw(balance, amount):
if amount > balance:
raise ValueError("余额不足")
return balance - amount
balance = deposit(balance, 500)
balance = withdraw(balance, 200)
print(balance)
Object-oriented implementation:
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("余额不足")
self.balance -= amount
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.balance)
Both approaches can accomplish the same business.
The main differences are:
| Comparison Dimension | Procedural | Object-Oriented |
|---|---|---|
| Organization approach | Functions and execution steps | Classes and objects |
| Data management | Data usually exists independently | Data and behavior can be encapsulated |
| Code reuse | Function reuse | Class, object, and composition reuse |
| State management | Through parameter passing and external variables | Objects store their own state |
| Extension approach | Add functions or adjust the flow | Add classes, compose objects, or extend behavior |
| Applicable scenarios | Tasks with clear processes and smaller scale | Complex domain models and state management |
Object-oriented programming is not a replacement for procedural programming. Python is a multi-paradigm language, and real-world projects often use functional, procedural, and object-oriented programming approaches at the same time.
II. Classes and Objects
Classes and objects are the two most fundamental concepts in object-oriented programming.
- Class: describes the attributes and behavior of a category of things and is the definition used to create objects.
- Object: a concrete instance of a class that has its own state and can perform the corresponding behavior.
You can think of a class as a blueprint and an object as a concrete entity created from the blueprint.
1. Defining a Class
Python uses the class keyword to define a class.
class Person:
pass
Here, a class named Person is defined.
pass is a placeholder statement, indicating that no concrete content has been implemented yet.
Class names typically use PascalCase (upper camel case):
class User:
pass
class BankAccount:
pass
class ShoppingCart:
pass
2. Creating Objects
After a class is defined, objects can be created by calling the class.
class Person:
pass
person1 = Person()
person2 = Person()
print(person1)
print(person2)
print(type(person1))
print(isinstance(person1, Person))
Output is similar to:
<__main__.Person object at 0x...>
<__main__.Person object at 0x...>
<class '__main__.Person'>
True
Person() creates an instance of the Person class.
person1 and person2 reference two independent objects, respectively.
class Person:
pass
person1 = Person()
person2 = Person()
print(person1 is person2)
Output:
False
Here, is is used to determine whether two variables reference the same object.
3. Relationship Between Classes and Objects
A class can create multiple objects. Each object has the same basic structure but can have a different state.
class Dog:
pass
dog1 = Dog()
dog2 = Dog()
dog3 = Dog()
The relationship can be represented as:
flowchart TD
A["Dog class"] --> B["dog1 object"]
A --> C["dog2 object"]
A --> D["dog3 object"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that a class is not a physical template replica of an object. In Python, a class itself is also an object; it can be assigned, passed around, have its attributes modified, and can also be created dynamically at runtime.
III. Attributes and Methods
Objects usually consist of state and behavior.
- Attribute: describes the object's data and state.
- Method: describes the operations that an object can perform.
For example, a user object can have attributes such as name and age, along with methods such as login and change password.
1. Instance Attributes
Instance attributes belong to a particular object, and different objects can have different instance attribute values.
Instance attributes are usually defined in the __init__() method using self.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(person1.name)
print(person1.age)
print(person2.name)
print(person2.age)
Output:
Alice
25
Bob
30
Here:
self.namerepresents the current object'snameattribute.self.agerepresents the current object'sageattribute.person1andperson2each store their own attribute values.
2. Instance Methods
An instance method is an ordinary method defined in a class, and its first parameter is usually self.
class Person:
def __init__(self, name):
self.name = name
def introduce(self):
print(f"大家好,我叫 {self.name}")
person = Person("Alice")
person.introduce()
Output:
大家好,我叫 Alice
Calling:
person.introduce()
can be understood as:
Person.introduce(person)
When an ordinary instance method is accessed through an instance, Python passes the instance as the first parameter.
3. Relationship Between Attributes and Methods
Attributes describe an object's state, while methods operate on that state.
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
def reset(self):
self.value = 0
def get_value(self):
return self.value
counter = Counter()
counter.increment()
counter.increment()
print(counter.get_value())
counter.reset()
print(counter.get_value())
Output:
2
0
Objects manage their own state through methods, so callers do not need to be directly involved in all internal operations.
IV. Constructors and Initialization Methods
Creating an object in Python involves two important methods:
__new__(): responsible for creating and returning the instance object.__init__(): responsible for initializing the instance that has already been created.
1. The init() initialization method
__init__() is the most common initialization method.
class User:
def __init__(self, username, email):
self.username = username
self.email = email
user = User("alice", "alice@example.com")
print(user.username)
print(user.email)
When the following is executed:
user = User("alice", "alice@example.com")
Python first creates the instance, then calls the initialization method to set the instance state.
__init__() must return None; it cannot replace the created instance by returning another object.
2. new() creates an instance
__new__() is a special method responsible for creating the object.
class Person:
def __new__(cls, *args, **kwargs):
print("创建对象")
instance = super().__new__(cls)
return instance
def __init__(self, name):
print("初始化对象")
self.name = name
person = Person("Alice")
Output:
创建对象
初始化对象
Here:
clsrepresents the class whose instance is currently being created.super().__new__(cls)calls the parent class's object creation logic.- The instance returned by
__new__()then participates in initialization.
If the object returned by __new__() is not an instance of the current class or one of its subclasses, the current class's __init__() is usually not called afterward.
3. Object creation process
flowchart TD
A["Call class Person"] --> B["Execute __new__"]
B --> C["Create and return instance"]
C --> D{"Does the returned object belong to the target class or its subclass?"}
D -->|Yes| E["Execute __init__"]
D -->|No| F["Do not execute the current class's __init__"]
E --> G["Return the instance object"]
F --> H["Return the result of __new__"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
4. Differences between new() and init()
| Comparison aspect | __new__() |
__init__() |
|---|---|---|
| Main responsibility | Create an instance | Initialize the instance |
| First parameter position | cls |
self |
| When it is called | Before initialization | After the instance is created |
| Return value | Usually returns the instance | Must return None |
| Common uses | Special instance creation, customization of immutable types | Set instance attributes |
In everyday business development, you usually only need to write __init__().
5. The role of self
self is the conventional first parameter in Python instance methods, used to reference the current instance.
It is not a Python keyword, but an ordinary parameter name. Although syntactically it can be replaced with another name, doing so is not recommended.
1. self refers to the current instance
class Student:
def __init__(self, name):
self.name = name
def study(self):
print(f"{self.name} 正在学习")
student = Student("Alice")
student.study()
Call:
student.study()
is equivalent to:
Student.study(student)
Therefore, self refers to the specific instance that calls the method.
2. self is used to access instance attributes
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def show(self):
print(self.name)
print(self.price)
product = Product("Keyboard", 299)
product.show()
3. self is not a fixed object identity
When the same instance calls a method, self refers to that instance.
When different instances call the same method, self refers to different instances respectively.
class Counter:
def __init__(self, value):
self.value = value
def show(self):
print(self.value)
a = Counter(10)
b = Counter(20)
a.show()
b.show()
Output:
10
20
Instance methods are not copied separately for each object; rather, the class usually provides the method function, which is called after being bound to an instance.
VI. Class Attributes and Instance Attributes
In Python, attributes can belong to a class or to an instance.
1. Class attributes
Class attributes are defined in the class namespace and are usually shared by all instances of that class.
class Student:
school = "Python Academy"
def __init__(self, name):
self.name = name
student1 = Student("Alice")
student2 = Student("Bob")
print(Student.school)
print(student1.school)
print(student2.school)
Output:
Python Academy
Python Academy
Python Academy
All three access expressions can read the class attribute.
2. Instance attributes
Instance attributes belong to a specific instance.
class Student:
school = "Python Academy"
def __init__(self, name):
self.name = name
student1 = Student("Alice")
student2 = Student("Bob")
print(student1.name)
print(student2.name)
The two objects have different name attributes.
3. Differences between class attributes and instance attributes
| Aspect | Class attribute | Instance attribute |
|---|---|---|
| Definition location | Class namespace | Instance namespace |
| Object it belongs to | Class | Specific instance |
| Access method | Class or instance | Instance |
| Default sharing | All instances share the same class attribute object | Each instance stores it independently |
| Typical use | Shared configuration, statistical information | The object's own state |
4. Attribute lookup mechanism
Access:
student.name
Python looks up the corresponding name according to the attribute access rules.
For ordinary instance attribute reads, an important simplified understanding is:
- Check data descriptors first.
- Check the instance's own attribute namespace.
- Check attributes in the class and its inheritance hierarchy.
- Complete the corresponding access according to descriptor rules.
Therefore, it cannot simply be assumed that in all cases instance attributes are checked first and then class attributes. The descriptor mechanism affects attribute lookup precedence.
5. An instance attribute with the same name overrides the class attribute for reads
class Student:
school = "Python Academy"
student = Student()
print(student.school)
student.school = "AI Academy"
print(student.school)
print(Student.school)
Output:
Python Academy
AI Academy
Python Academy
This assignment:
student.school = "AI Academy"
usually creates an attribute with the same name in the instance's own namespace, rather than modifying the class attribute.
Therefore, other instances still read the original class attribute value.
6. Sharing Issues with Mutable Class Attributes
If a class attribute points to a mutable object, you need to be especially careful.
class Student:
courses = []
def add_course(self, course):
self.courses.append(course)
student1 = Student()
student2 = Student()
student1.add_course("Python")
print(student1.courses)
print(student2.courses)
Output:
['Python']
['Python']
The reason is that both instances access the same class attribute list.
If you want each student to have an independent course list, you should define an instance attribute:
class Student:
def __init__(self):
self.courses = []
def add_course(self, course):
self.courses.append(course)
student1 = Student()
student2 = Student()
student1.add_course("Python")
print(student1.courses)
print(student2.courses)
Output:
['Python']
[]
This is a very common mistake in Python object-oriented programming.
7. Instance Methods, Class Methods, and Static Methods
There are three common types of methods in Python classes:
- Instance methods.
- Class methods.
- Static methods.
They differ in the object they are bound to when called and in their use cases.
1. Instance Methods
Instance methods access instance state through self.
class User:
def __init__(self, name):
self.name = name
def introduce(self):
return f"我是 {self.name}"
user = User("Alice")
print(user.introduce())
They are suitable for operating on the data of a specific instance.
2. Class Methods
Class methods are defined using the @classmethod decorator; their first parameter is usually cls, which represents the class to which the current call is bound.
class User:
role = "member"
def __init__(self, name):
self.name = name
@classmethod
def get_role(cls):
return cls.role
print(User.get_role())
Class methods are suitable for operating on class-level state and are often used to define alternative constructors.
For example:
class User:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def from_string(cls, text):
name, age = text.split(",")
return cls(name, int(age))
user = User.from_string("Alice,25")
print(user.name)
print(user.age)
Here, cls(...) is used to create the object rather than hardcoding User(...), so when a subclass calls this method, it can also create an instance of the corresponding subclass.
3. Static Methods
Static methods are defined using the @staticmethod decorator.
They do not automatically receive a self or cls parameter.
class MathUtils:
@staticmethod
def add(a, b):
return a + b
print(MathUtils.add(10, 20))
Static methods are typically used for utility functions that are logically related to the class but do not need to access instance state or class state.
4. Comparison of the Three Method Types
| Method Type | Decorator | First Parameter | Automatically Binds to Instance or Class |
|---|---|---|---|
| Instance method | None | self |
Binds to instance |
| Class method | @classmethod |
cls |
Binds to class |
| Static method | @staticmethod |
No special requirement | Does not automatically bind to instance or class |
5. Comprehensive Example
class Employee:
company = "OpenTech"
def __init__(self, name, salary):
self.name = name
self.salary = salary
def introduce(self):
return f"{self.name} 在 {self.company} 工作"
@classmethod
def change_company(cls, company):
cls.company = company
@staticmethod
def is_valid_salary(salary):
return salary >= 0
employee = Employee("Alice", 12000)
print(employee.introduce())
Employee.change_company("AI Tech")
print(employee.introduce())
print(Employee.is_valid_salary(12000))
The three method types can be used separately according to their responsibilities; there is no need to force all of them to be defined as instance methods just for stylistic consistency.
8. Encapsulation: Organizing an Object's Internal State
Encapsulation is one of the important ideas in object-oriented programming.
It emphasizes organizing data and the behaviors that operate on that data together, and managing an object's internal state through a clear interface.
1. Why Encapsulation Is Needed
Suppose a bank account directly exposes its balance:
class BankAccount:
def __init__(self, balance):
self.balance = balance
account = BankAccount(1000)
account.balance = -100000
This approach allows external code to modify the balance directly, which may violate business rules.
State changes can be controlled through methods:
class BankAccount:
def __init__(self, balance=0):
if balance < 0:
raise ValueError("初始余额不能为负数")
self._balance = balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("存款金额必须大于零")
self._balance += amount
def withdraw(self, amount):
if amount <= 0:
raise ValueError("取款金额必须大于零")
if amount > self._balance:
raise ValueError("余额不足")
self._balance -= amount
def get_balance(self):
return self._balance
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())
Output:
1300
Balance changes are made through explicit methods, allowing business validation to be centralized.
2. Python's Access Control Conventions
Unlike Java, Python does not use private, protected, and public keywords to enforce access control for ordinary attributes.
Python mainly uses naming conventions to express access intent.
| Notation | Meaning |
|---|---|
name |
Public attribute |
_name |
Conventionally for internal use |
__name |
Triggers name mangling |
__name__ |
Typically used for special methods and special attributes |
For example:
class User:
def __init__(self, name, password):
self.name = name
self._email = "alice@example.com"
self.__password = password
Here:
nameis a public attribute._emailindicates an internal-use convention.__passwordtriggers name mangling.
Note that neither single underscores nor double underscores are an absolutely secure access-control mechanism.
3. Double Underscore Name Mangling
For __password defined in a class, Python usually rewrites it into a form that includes the class name.
class User:
def __init__(self, password):
self.__password = password
user = User("secret")
print(user._User__password)
Output:
secret
This shows that the main role of double underscores is name mangling (Name Mangling), used to reduce the probability of attribute name conflicts in subclasses, rather than providing a truly secure private mechanism.
4. Using property to Manage Attributes
Python provides property, which can wrap methods into an attribute-like access interface.
class Product:
def __init__(self, price):
self._price = price
@property
def price(self):
return self._price
@price.setter
def price(self, value):
if value < 0:
raise ValueError("价格不能为负数")
self._price = value
product = Product(100)
print(product.price)
product.price = 200
print(product.price)
Callers access data through attribute syntax, but validation logic can still be executed internally.
property is suitable for controlling how attributes are read and modified while keeping the interface concise.
IX. Inheritance: Reusing and Extending Classes
Inheritance allows a class to be defined based on another class, thereby obtaining the attributes and methods provided by the parent class.
The class being inherited from is usually called the parent class, base class, or superclass.
A class that inherits from other classes is usually called a child class or derived class.
1. Basic Inheritance
class Animal:
def eat(self):
print("动物正在进食")
def sleep(self):
print("动物正在睡觉")
class Dog(Animal):
def bark(self):
print("汪汪汪")
dog = Dog()
dog.eat()
dog.sleep()
dog.bark()
Output:
动物正在进食
动物正在睡觉
汪汪汪
Dog inherits from Animal, so it can use the methods provided by the parent class while also defining its own behavior.
2. Inheritance Relationships
flowchart TD
A["Animal parent class"] --> B["Dog subclass"]
A --> C["Cat subclass"]
A --> D["Bird subclass"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
3. Method Overriding
A subclass can redefine a method already defined in the parent class; this is called method overriding (Method Overriding).
class Animal:
def speak(self):
print("动物发出声音")
class Dog(Animal):
def speak(self):
print("汪汪汪")
class Cat(Animal):
def speak(self):
print("喵喵喵")
dog = Dog()
cat = Cat()
dog.speak()
cat.speak()
Output:
汪汪汪
喵喵喵
After a subclass overrides a method, calling that method through a subclass instance uses the subclass's own implementation.
4. Using super()
super() is used to access the next implementation in the inheritance hierarchy according to the method resolution order (MRO).
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("动物发出声音")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
super().speak()
print("汪汪汪")
dog = Dog("Buddy", "Golden Retriever")
print(dog.name)
print(dog.breed)
dog.speak()
Output:
Buddy
Golden Retriever
动物发出声音
汪汪汪
super() is not simply equivalent to directly calling the parent class; rather, it finds the next applicable implementation according to the method resolution order.
This is especially important in multiple inheritance.
5. Multiple Inheritance
Python supports a class inheriting from multiple parent classes at the same time.
class Flyable:
def fly(self):
print("正在飞行")
class Swimmable:
def swim(self):
print("正在游泳")
class Duck(Flyable, Swimmable):
pass
duck = Duck()
duck.fly()
duck.swim()
Output:
正在飞行
正在游泳
Multiple inheritance can combine the behaviors of multiple classes, but it also increases the complexity of inheritance relationships.
6. Method Resolution Order (MRO)
When multiple parent classes have methods with the same name, Python needs to determine which method to call.
This is determined by the Method Resolution Order (MRO).
class A:
def show(self):
print("A")
class B(A):
def show(self):
print("B")
class C(A):
def show(self):
print("C")
class D(B, C):
pass
print(D.mro())
d = D()
d.show()
Output:
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>]
B
Python uses the C3 linearization algorithm to calculate the MRO, ensuring the ordering constraints in the inheritance relationships.
You can use:
D.__mro__
to view the method resolution order of a class.
10. Polymorphism: Same Interface, Different Behavior
Polymorphism means that objects of different types can exhibit different behaviors through a unified interface.
Python is a dynamically typed language and usually implements polymorphism through duck typing and method overriding.
1. Basic Polymorphism
class Dog:
def speak(self):
return "汪汪汪"
class Cat:
def speak(self):
return "喵喵喵"
class Duck:
def speak(self):
return "嘎嘎嘎"
def make_sound(animal):
print(animal.speak())
animals = [
Dog(),
Cat(),
Duck(),
]
for animal in animals:
make_sound(animal)
Output:
汪汪汪
喵喵喵
嘎嘎嘎
make_sound() does not need to know which class the passed-in object specifically belongs to; it only needs the object to provide a callable speak() method.
2. The Core Value of Polymorphism
Polymorphism allows the caller to depend on a unified interface rather than on a specific implementation.
For example:
class EmailNotification:
def send(self, message):
print(f"发送邮件:{message}")
class SMSNotification:
def send(self, message):
print(f"发送短信:{message}")
class PushNotification:
def send(self, message):
print(f"发送推送:{message}")
def notify(service, message):
service.send(message)
notify(EmailNotification(), "订单已创建")
notify(SMSNotification(), "订单已创建")
notify(PushNotification(), "订单已创建")
When adding new notification channels in the future, as long as they provide a compatible send() method, callers usually do not need to be modified.
3. The Relationship Between Polymorphism and Inheritance
Polymorphism does not necessarily require inheritance.
For example:
class FileLogger:
def write(self, message):
print("写入文件:", message)
class ConsoleLogger:
def write(self, message):
print("输出控制台:", message)
def log_message(logger, message):
logger.write(message)
log_message(FileLogger(), "程序启动")
log_message(ConsoleLogger(), "程序启动")