如何在Python中编写简洁规范的__init__方法?
优化Python中冗长__init__方法的几种方案
针对你给出的Detect类__init__方法,这里提供几个简洁规范的优化思路:
1. 分离类级默认属性
把不需要随实例变化的固定默认值(比如阈值、颜色、初始状态变量)定义为类属性,避免在__init__里重复初始化,既减少代码量,又方便统一修改:
import cv2 as cv class Detect: """Class to show frames""" # 类级默认属性,所有实例共享(可被实例单独覆盖) classes_names = [] previous_time = 0 authorised = True first_time = 0 first_detect_time = 0 color = (255, 0, 255) conf_threshold = 0.5 nms_threshold = 0.3 def __init__(self, main_target, target_object, camera, sms_class, qr_code_class, cuda="CPU"): # 仅处理实例独有的参数 self.main_target = main_target self.target_object = target_object self.camera = camera self.sms_class = sms_class self.qr_code_class = qr_code_class self.cuda = cuda # 依赖实例参数的初始化 self.capture = cv.VideoCapture(self.camera)
2. 批量赋值实例参数
如果参数较多,可通过参数列表批量绑定到self,避免重复写self.x = x:
import cv2 as cv class Detect: """Class to show frames""" # 类级默认属性 classes_names = [] previous_time = 0 authorised = True first_time = 0 first_detect_time = 0 color = (255, 0, 255) conf_threshold = 0.5 nms_threshold = 0.3 def __init__(self, main_target, target_object, camera, sms_class, qr_code_class, cuda="CPU"): # 批量绑定参数到self param_list = ["main_target", "target_object", "camera", "sms_class", "qr_code_class", "cuda"] for param in param_list: setattr(self, param, locals()[param]) self.capture = cv.VideoCapture(self.camera)
3. 使用dataclass自动生成__init__
Python 3.7+的dataclasses模块可自动生成__init__方法,支持默认值,代码更简洁:
from dataclasses import dataclass import cv2 as cv @dataclass class Detect: """Class to show frames""" # 实例参数,带默认值的放在后面 main_target: object target_object: object camera: int | str sms_class: object qr_code_class: object cuda: str = "CPU" # 类级默认属性 classes_names = [] previous_time = 0 authorised = True first_time = 0 first_detect_time = 0 color = (255, 0, 255) conf_threshold = 0.5 nms_threshold = 0.3 def __post_init__(self): # 处理依赖实例参数的初始化逻辑 self.capture = cv.VideoCapture(self.camera)
综合优化后的推荐版本
结合可读性与简洁性,推荐使用类级默认属性+dataclass的组合,既减少重复代码,又保持逻辑清晰:
from dataclasses import dataclass import cv2 as cv @dataclass class Detect: """Class to handle frame detection""" main_target: object target_object: object camera: int | str sms_class: object qr_code_class: object cuda: str = "CPU" # 类级默认配置与状态变量 classes_names = [] previous_time = 0 authorised = True first_time = 0 first_detect_time = 0 color = (255, 0, 255) conf_threshold = 0.5 nms_threshold = 0.3 def __post_init__(self): self.capture = cv.VideoCapture(self.camera)
补充说明:
- 类级属性若需在实例中修改,直接赋值即可(如
detect_instance.color = (0,255,0)),不会影响其他实例。 __post_init__是dataclass提供的钩子,用于处理无法直接在字段定义中完成的初始化逻辑。- 若Python版本低于3.7,可使用
attrs库替代dataclasses,用法类似。
内容的提问来源于stack exchange,提问作者Novin.Nouri
相关产品推荐
相关产品推荐

