一、OOP 核心概念
-
类 (Class)
- 对象的蓝图,定义属性和方法的集合
- 使用
class
关键字定义:class Dog: pass
-
对象 (Object)
- 类的实例化实体,包含具体数据
- 通过调用类创建:
my_dog = Dog()
-
四大特性
- 封装:隐藏内部实现细节,通过方法暴露操作
- 继承:子类复用父类功能
- 多态:不同对象对相同方法的不同实现
- 抽象:定义接口规范(通过 ABCs 实现)
二、类结构详解
1. 初始化方法
class Dog:
def __init__(self, name, age):
self.name = name # 实例属性
self.age = age
self._secret = "私有属性" # 约定式私有属性(单下划线)
self.__real_secret = "强私有" # 名称修饰(双下划线)
2. 实例方法
def bark(self):
print(f"{self.name} says woof!")
3. 类方法
@classmethod
def from_birth_year(cls, name, year):
age = datetime.date.today().year - year
return cls(name, age)
4. 静态方法
@staticmethod
def is_adult(age):
return age > 3
5. 属性装饰器
@property
def human_age(self):
return self.age * 7
@human_age.setter
def human_age(self, value):
self.age = value // 7
三、继承与多态
1. 基础继承
class Bulldog(Dog):
def __init__(self, name, age, weight):
super().__init__(name, age)
self.weight = weight
# 方法重写
def bark(self):
print("Woof! (deep voice)")
2. 多重继承
class Robot:
def beep(self):
print("Beep!")
class RoboDog(Dog, Robot):
pass
3. 方法解析顺序 (MRO)
print(RoboDog.__mro__) # 查看继承顺序
四、高级特性
1. 抽象基类 (ABCs)
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def make_sound(self):
pass
2. 魔法方法
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 __str__(self):
return f"Vector({self.x}, {self.y})"
3. 类属性与实例属性
class MyClass:
class_attr = 10 # 类属性(所有实例共享)
def __init__(self):
self.instance_attr = 20 # 实例属性
4. 动态属性
class DynamicClass:
def __getattr__(self, name):
return f"Property {name} doesn't exist"
def __setattr__(self, name, value):
print(f"Setting {name} to {value}")
super().__setattr__(name, value)
五、设计模式实现
1. 单例模式
class Singleton:
_instance = None
def __new__(cls):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
2. 工厂模式
class AnimalFactory:
@staticmethod
def create_animal(animal_type):
if animal_type == "dog":
return Dog()
elif animal_type == "cat":
return Cat()
raise ValueError("Invalid animal type")
六、最佳实践
-
组合优于继承
class Engine: def start(self): print("Engine started") class Car: def __init__(self): self.engine = Engine()
-
使用
super()
调用父类方法class Child(Parent): def __init__(self, param): super().__init__(param) # 添加子类初始化
-
鸭子类型实现多态
def animal_sound(animal): animal.make_sound() # 只要实现 make_sound 方法即可
-
避免可变默认参数
# 错误示例 def __init__(self, items=[]): self.items = items # 正确做法 def __init__(self, items=None): self.items = items if items is not None else []
七、调试技巧
- 查看对象属性:
vars(obj)
- 检查继承关系:
issubclass()
- 判断对象类型:
isinstance()
- 动态添加方法:
def new_method(self): print("New method") MyClass.new_method = new_method