Home > database >  Setting instance variables in a factory method
Setting instance variables in a factory method

Time:01-10

The problem in code:

class Object:
  def __init__(self, x, y):
    self.a = some_logic(x)
    self.b = some_logic(y)

  @classmethod
  def produce_object(cls, x, y, additional_knowledge) -> 'Object':
    a = some_different_logic(x, additional_knowledge)
    b = some_different_logic(y, additional_knowledge)
    # now how to initialize Object?
    # bad ( I dont want to call some_logic):
    o = Object(x, y)
    o.a = x
    o.b = y
    return o

I want to create a new instance, that creates it in another way than the constructor does. For this alternative way I would maybe use some additional knowledge that allows me to call produce_object (which spares me a lot of expensive calculations located in the constructor).

In Java I would place the a and b instance variables outside the constructor in the body of the class. If I do this in python, they are treated as static members.

Do i have to do something like this ?:

class Object:
  def __init__(self):
    self.a = None
    self.b = None

  def former_constructor(self, x, y):
    self.a = some_logic(x)
    self.b = some_logic(y)
   
  def produce_object(self, x, y):
    self.a = some_different_logic(x)
    self.b = some_different_logic(y)

My best guess (since you cant have multiple constructors, right?) that one would write a very generic constructor. This of course leads to complicated code in the real world (imagine you have 3 ways to calculate your stuff. One takes arguments of type A and B, second C and D, third E and F. But you always have to provide everything (with potentially four Nones).

Any comment on this is very appreciatied. Thanks for you help.

CodePudding user response:

The @classmethod approach can be modified to provide an alternative constructor which does not invoke the default constructor (init). Instead, an instance is created using new.

According to @Andrzej Pronobis

  •  Tags:  
  • Related