Python面向对象编程(OOP)
一、类与对象基础
- 类定义与实例化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Dog: """Dog类的简单示例""" species = "Canis familiaris" def __init__(self, name, age): """初始化方法(构造函数)""" self.name = name self.age = age def description(self): """实例方法""" return f"{self.name} is {self.age} years old" def speak(self, sound): """带参数的实例方法""" return f"{self.name} says {sound}"
my_dog = Dog("Buddy", 5) print(my_dog.description()) print(my_dog.speak("Woof!"))
|
- 类与实例命名空间
• 类属性:所有实例共享,通过类或实例访问
• 实例属性:每个实例独有,优先于类属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Example: class_attr = "类属性值" def __init__(self, instance_attr): self.instance_attr = instance_attr
obj1 = Example("实例1") obj2 = Example("实例2")
print(obj1.class_attr) print(obj1.instance_attr)
Example.class_attr = "修改后的类属性" print(obj2.class_attr)
|
- 属性访问控制
Python中没有真正的私有属性,但有以下约定:
• 公有属性:normal_name
• 保护属性:_protected_name
(约定,实际仍可访问)
• 私有属性:__private_name
(名称修饰,实际变为_ClassName__private_name
)
1 2 3 4 5 6 7 8 9 10 11
| class AccessExample: def __init__(self): self.public = "公共属性" self._protected = "保护属性" self.__private = "私有属性"
obj = AccessExample() print(obj.public) print(obj._protected)
print(obj._AccessExample__private)
|
二、继承与多态
- 基本继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Animal: def __init__(self, name): self.name = name def speak(self): raise NotImplementedError("子类必须实现此方法")
class Dog(Animal): def speak(self): return f"{self.name} says Woof!"
class Cat(Animal): def speak(self): return f"{self.name} says Meow!"
animals = [Dog("Buddy"), Cat("Misty")] for animal in animals: print(animal.speak())
|
- 方法重写与super()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Parent: def __init__(self, name): self.name = name def show(self): print(f"Parent method: {self.name}")
class Child(Parent): def __init__(self, name, age): super().__init__(name) self.age = age def show(self): super().show() print(f"Child method: {self.name}, {self.age}")
child = Child("Alice", 10) child.show()
|
- 多重继承与方法解析顺序(MRO)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| 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
d = D() d.show() print(D.mro())
|
三、特殊方法与运算符重载
- 常用特殊方法
方法 |
描述 |
调用方式 |
__init__ |
构造函数 |
obj = Class() |
__str__ |
字符串表示 |
str(obj) , print(obj) |
__repr__ |
官方字符串表示 |
repr(obj) |
__len__ |
长度 |
len(obj) |
__getitem__ |
索引访问 |
obj[key] |
__setitem__ |
索引赋值 |
obj[key] = value |
__delitem__ |
索引删除 |
del obj[key] |
__iter__ |
迭代器协议 |
for x in obj |
__eq__ |
相等比较 |
obj == other |
__add__ |
加法运算 |
obj + other |
- 实现示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __sub__(self, other): return Vector(self.x - other.x, self.y - other.y) def __mul__(self, scalar): return Vector(self.x * scalar, self.y * scalar) def __eq__(self, other): return self.x == other.x and self.y == other.y def __str__(self): return f"Vector({self.x}, {self.y})" def __repr__(self): return f"Vector({self.x}, {self.y})"
v1 = Vector(2, 3) v2 = Vector(4, 5) print(v1 + v2) print(v1 * 3)
|
四、类方法与静态方法
- 实例方法 vs 类方法 vs 静态方法
类型 |
装饰器 |
第一个参数 |
访问权限 |
实例方法 |
无 |
self (实例引用) |
可访问实例和类 |
类方法 |
@classmethod |
cls (类引用) |
只能访问类 |
静态方法 |
@staticmethod |
无 |
无特殊访问权限 |
- 实现示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class MyClass: class_attr = "类属性" def __init__(self, instance_attr): self.instance_attr = instance_attr def instance_method(self): print(f"实例方法访问: {self.instance_attr}, {self.class_attr}") @classmethod def class_method(cls): print(f"类方法访问: {cls.class_attr}") @staticmethod def static_method(): print("静态方法无需访问类或实例")
obj = MyClass("实例属性") obj.instance_method() MyClass.class_method() MyClass.static_method()
|
五、属性装饰器与描述符
- 属性装饰器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Circle: def __init__(self, radius): self._radius = radius @property def radius(self): """获取半径""" return self._radius @radius.setter def radius(self, value): """设置半径,必须为正数""" if value <= 0: raise ValueError("半径必须为正数") self._radius = value @property def area(self): """计算面积(只读属性)""" return 3.14 * self._radius ** 2
circle = Circle(5) print(circle.radius) circle.radius = 10 print(circle.area)
|
- 描述符协议
描述符是实现__get__
、__set__
或__delete__
方法的类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class PositiveNumber: def __init__(self, name): self.name = name def __get__(self, instance, owner): return instance.__dict__[self.name] def __set__(self, instance, value): if value <= 0: raise ValueError("必须为正数") instance.__dict__[self.name] = value
class Rectangle: width = PositiveNumber("width") height = PositiveNumber("height") def __init__(self, width, height): self.width = width self.height = height
rect = Rectangle(10, 20) print(rect.width)
|
六、抽象基类(ABC)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| from abc import ABC, abstractmethod
class Shape(ABC): @abstractmethod def area(self): pass @abstractmethod def perimeter(self): pass
class 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)
rect = Rectangle(5, 10) print(rect.area())
|
七、常见设计模式实现
- 单例模式
1 2 3 4 5 6 7 8 9 10 11
| class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance
a = Singleton() b = Singleton() print(a is b)
|
- 工厂模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| class Dog: def speak(self): return "Woof!"
class Cat: def speak(self): return "Meow!"
def get_pet(pet="dog"): pets = { "dog": Dog(), "cat": Cat() } return pets[pet]
dog = get_pet("dog") print(dog.speak())
|
- 观察者模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Subject: def __init__(self): self._observers = [] def attach(self, observer): self._observers.append(observer) def detach(self, observer): self._observers.remove(observer) def notify(self): for observer in self._observers: observer.update(self)
class Observer: def update(self, subject): pass
class TemperatureSensor(Subject): def __init__(self): super().__init__() self._temperature = 0 @property def temperature(self): return self._temperature @temperature.setter def temperature(self, value): self._temperature = value self.notify()
class Display(Observer): def update(self, subject): print(f"温度更新: {subject.temperature}°C")
sensor = TemperatureSensor() display = Display() sensor.attach(display)
sensor.temperature = 25 sensor.temperature = 30
|