class - Best practice python init check -
what best way initialize attributes , check provided parameters when initializing python class? suppose there multiple parameters in __init__()
, of them have comply rules. there need have setters , getters of them. can think of option below. how you? there better options?
option: initialize attributes none
, call setter, check performed.
class a(object): def __init__(self, p1=none, ..., pn=none): self._p1 = none ... self._pn = none if p1 not none: self.p1 = p1 ... if pn not none: self.pn = pn @p1.setter def p1(self, p1): # if p1 int can take if isinstance(p1, int): self._p1 = p1 # if p1 str have obtain differently elif isinstance(p1, str): self._p1 = self._gen_some_p_from_str(p1) else: raise exception('incorrect p1 type provided.') ... @pn.setter def pn(self, pn): # if pn instance of someotherclass should great if isinstance(pn, someotherclass): if pn.great(): self._pn = pn else: raise exception('pn not great') # pn can str, , should elif isinstance(pn, str): self._pn = self._get_some_other_p_from_str(pn) else: raise exception('incorrect pn type provided.')
if need run validation on each assign, property way.
keep in mind might have performance issue when have many assignments(like in loop).
your issue can solved validate input on initiation of class, better have clean
or validate
method on class, call in end of __init__
func.
using method can call clean
method whenever need, , omit call performance more important validation(this how django forms works).
in case, trying overloading/dispatching, take @ docs
Comments
Post a Comment