Issue
I want write cleanly init method in python.
my init method is very long and dirty.
I don't know how can clean it.
and its my dirty code:
class Detect:
"""Class to show frames"""
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.classes_names = []
self.previous_time = 0
self.authorised = True
self.first_time = 0
self.first_detect_time = 0
self.color = (255, 0, 255)
self.capture = cv.VideoCapture(self.camera)
self.conf_threshold = 0.5
self.nms_threshold = 0.3
Solution
There are multiple ways to go about it, one is to define a base class and assign all those default values in the base class, and inherit Detect
from it. I've even further reduced the first part using **kwargs
and setattr
method:
class BaseDetect:
def __init__(self):
self.classes_names = []
self.previous_time = 0
self.authorised = True
self.first_time = 0
self.first_detect_time = 0
self.color = (255, 0, 255)
self.conf_threshold = 0.5
self.nms_threshold = 0.3
class Detect(BaseDetect):
"""Class to show frames"""
def __init__(self, cuda = "CPU", **kwargs):
self.cuda = cuda
super().__init__()
for key, value in kwargs.items():
setattr(self, key, value)
self.capture = cv.VideoCapture(self.camera)
It still has those codes of course but doesn't the child class look much cleaner now? Also, if those values are static and not going to change, it's just better to make them class variable, or global constants. That's also something you can try.
Answered By - ThePyGuy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.