📚 Python 面向对象编程(OOP)全面学习指南
面向对象编程是构建复杂程序的核心理念,掌握它能让代码更模块化、易维护。以下从基础到进阶,系统整理 Python OOP 的关键知识。
一、核心概念
1. 类(Class)与对象(Object)
- 类:对象的蓝图,定义属性和方法。
- 对象:类的实例,具备具体属性和行为。
class Dog:def __init__(self, name, age): self.name = name self.age = agedef bark(self): print(f"{self.name} 汪汪叫!")
my_dog = Dog("Buddy", 3)
my_dog.bark()
2. 面向对象四大特性
特性 | 描述 |
---|
封装 | 隐藏内部实现,通过方法暴露可控操作(如属性访问限制)。 |
继承 | 子类继承父类属性和方法,支持代码复用。 |
多态 | 同一接口在不同类中有不同实现(Python 通过鸭子类型实现)。 |
抽象 | 定义抽象类和接口,强制子类实现特定方法。 |
二、类的详解
1. 构造方法 __init__
class Student:def __init__(self, name, score):self.name = nameself.score = scorestudent = Student("Alice", 90)
2. 实例属性 vs 类属性
- 实例属性:属于对象,每个对象独立。
- 类属性:属于类,所有对象共享。
class Car:wheels = 4 def __init__(self, brand):self.brand = brand car1 = Car("Toyota")
car2 = Car("BMW")
print(Car.wheels)
3. 类方法与静态方法
- 类方法:操作类属性,使用
@classmethod
装饰器,第一个参数为 cls
。 - 静态方法:与类无关,使用
@staticmethod
装饰器。
class MyClass:class_attr = 0@classmethoddef increment_class_attr(cls):cls.class_attr += 1@staticmethoddef utility_method(a, b):return a + b
三、继承与多态
1. 单继承
class Animal:def speak(self):passclass Cat(Animal):def speak(self): print("喵喵~")class Dog(Animal):def speak(self):print("汪汪!")animals = [Cat(), Dog()]
for animal in animals:animal.speak()
2. 多继承与方法解析顺序(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):passd = D()
d.show()
print(D.mro())
四、封装与访问控制
1. 私有属性与方法
- 属性名以双下划线
__
开头,会被自动重命名(名称修饰)。
class BankAccount:def __init__(self, balance):self.__balance = balance def deposit(self, amount):if amount > 0:self.__balance += amountdef get_balance(self): return self.__balanceaccount = BankAccount(1000)
print(account.get_balance())
2. 使用 @property
控制属性访问
class Circle:def __init__(self, radius):self._radius = radius@propertydef radius(self): return self._radius@radius.setterdef radius(self, value): if value > 0:self._radius = valueelse:raise ValueError("半径必须为正数")circle = Circle(5)
circle.radius = 10
print(circle.radius)
五、高级主题
1. 抽象基类(ABC)
from abc import ABC, abstractmethodclass Shape(ABC):@abstractmethoddef area(self):passclass Circle(Shape):def __init__(self, radius):self.radius = radiusdef area(self):return 3.14 * self.radius ** 2
circle = Circle(5)
print(circle.area())
2. 魔术方法(Magic Methods)
方法 | 用途 | 示例 |
---|
__str__ | 定义 print(obj) 的输出 | def __str__(self): return "Text" |
__repr__ | 定义解释器输出 | def __repr__(self): return "Obj" |
__add__ | 重载 + 运算符 | def __add__(self, other): ... |
class Vector:def __init__(self, x, y):self.x = xself.y = ydef __add__(self, other):return Vector(self.x + other.x, self.y + other.y)def __str__(self):return f"Vector({self.x}, {self.y})"v1 = Vector(2, 3)
v2 = Vector(1, 4)
v3 = v1 + v2
print(v3)
六、实战案例
1. 简易电商系统
```python
class Product:def __init__(self, name, price):self.name = nameself.price = priceclass Cart:def __init__(self):self.items = []def add_item(self, product, quantity):self.items.append({"product": product, "quantity": quantity})def total_cost(self):return sum(item["product"].price * item["quantity"] for item in self.items)