constructor - How to handle missing args in python __init__? -
in multi-threaded implementation, need generate lots of instructions, pass them single processing thread. here custom instruction class:
class instruction: priority = 10 action = "" data = "" condition = "" target = "" ### constructor(s) declaration def __init__(self,priority=10,target="",action="",data="",condition=""): self.priority = priority self.target = target self.action = action self.data = data self.condition = condition
i have call different kinds of instructions, defined parameters may differ. 1 parameter missing, no target, no action, etc.
as current constructor, if call without target, i'll that:
i = instruction(priority_value,action_value,data_value,condition_value) print(i.priority) >>> priority_value print(i.target) >>> action_value print(i.action) >>> data_value print(i.target) >>> data_value print(i.data) >>> condition_value print(i.condition) >>> #nothing see here, move along!
i know can define custom constructors, like
@classmethod def notarget(priority=10,action=0,data="",condition=""): return instruction(priority,"",action,data,condition)
and call i=instruction.notarget(priority_value,action_value,data_value,condition_value)
but, there other ways that?
if so, please detail these? thanks!
sorry if mis-used or mis-spelled words, english isn't native language.
all parameters in function definition optional specified default parameters, don't have pass in values all.
when calling function, name arguments do want pass in; these called keyword arguments:
instruction(priority=priority_value, action=action_value, data=data_value, condition=condition_value)
when using keyword arguments in call, order doesn't matter, can mix them freely.
also see keyword arguments section of python tutorial.
Comments
Post a Comment