0

i have a python class in which i have few arguments sent to constructor as below.

class Test(object):
    def __init__(self, a, b):
        self.a = a
        if b<10:
            self.a = a*2

I know that, constructors are just meant to initialize variable's and there should be no logic inside a constructor. But, if not this way, how can i set value of "a" variable based a logic with "b" variable. I tried to use property. following is my code

class Test(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
    @property
    def a(self):
        self._a
    @a.setter
    def a(self, value):
        if self.b < 10:
            self._a = value*2
        else:
            self._a = value

But, problem is that, setter is not called when initializing with a constructor. So, how can i solve this problem of modifying the default setting of few variable inside a constructor

rawwar
  • 4,834
  • 9
  • 32
  • 57
  • how about doing logic before the constructor? `if b < 10: a = a*2 Test(a, b)`? – Simas Joneliunas Jul 11 '18 at 11:54
  • 4
    There's no such rule. Put whatever you like into init, as long as it's clear. – Daniel Roseman Jul 11 '18 at 11:54
  • @DanielRoseman, is there good way to do this, may be overriding default getter setter ? – rawwar Jul 11 '18 at 11:56
  • Thing is, i have to set almost 10 other instance variables based on one of the parameter.Also, the logic is not just one if-else, its a ladder of if-else loops. so, i thought it would be cleaner if i can make use of some construct so that logic would be applied to all the variables i want – rawwar Jul 11 '18 at 11:59
  • @SimasJoneliunas, problem is, its not just one variable that i want to update. i want to update multiple variables based on b – rawwar Jul 11 '18 at 12:16
  • `self.a` was never called since it's missing the `()` at the end? – Miket25 Jul 11 '18 at 12:17
  • I think i get it, @Miket25, thanks. i think, instead of doing self.a = a, i should do self.a(a). am i right – rawwar Jul 11 '18 at 12:23
  • 1
    The second example, the setter method doesn't know what `self.b` until it become set. Swap the ordering of the two lines in the `__init__` so that `b` is set before `a`. Note that `a` and `_a` will be different. – Miket25 Jul 11 '18 at 12:37

0 Answers0