0

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.

Mika Prouk
  • 495
  • 5
  • 16
  • Check **@Ber** answer to the question [What is a clean, Pythonic way to have multiple constructors in Python?](https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python) – pedro_bb7 Jan 09 '22 at 12:48
  • One answer illustrates how a classmethod from_x avoids calling the constructor. This is exactly what I need. Pity I cannot accept a comment as answer. – Mika Prouk Jan 09 '22 at 12:52

1 Answers1

1

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

pedro_bb7
  • 1,601
  • 3
  • 12
  • 28
  • 1
    Makes it easier for others if you link directly to [Andrzej Pronobis answer](https://stackoverflow.com/questions/682504/what-is-a-clean-pythonic-way-to-have-multiple-constructors-in-python/38885481#38885481) – DarrylG Jan 09 '22 at 14:46
  • Thanks, that was my intention, now understood how to do it. – pedro_bb7 Jan 09 '22 at 19:21