0

What is the good practice in Python when I need to initialize an objects that contains, for example, big array and it should be filled with calculated values during the object creation. Is it ok in Python to do this inside constructor or this is like a code-smell and I should use Factory instead? What is the Pythonic way here?

Brans
  • 649
  • 1
  • 7
  • 20
  • Are the contents of the array constant, or will each instance of the object get a unique array? FWIW, this question will probably get closed as "primarily opinion-based". Assuming that each instance gets a unique array, I'd initialize it directly in `__init__` if it can be done in a line or two, otherwise I'd call another method to initialize it. – PM 2Ring Dec 14 '16 at 09:56
  • - each instance of the object get a unique array it size and content is calculated during object creation. In c# I would create static method CreateX for this object creation and hide the constructor but in Python there is no private constructors so I doubht. – Brans Dec 14 '16 at 10:09
  • Do you intend to be able to transparently change class of objects being created? If yes, go with factory pattern. Otherwise I would consider, whether the code would be cleaner (more readable) if the calculations are outsourced to the factory class. – abukaj Dec 14 '16 at 10:26

1 Answers1

1

If you can initialize the array in a couple of lines of clear code then it's quite ok to initialize it directly in the __init__ method. Otherwise, initialize it in a separate method.

Python does have static methods and class methods (see here for some simple examples). You could use a static method to initialize your array, but if the initializer method uses attributes of the instance in its calculation you may as well make it a normal method, otherwise you'll need to pass it those values as parameters.

Python doesn't have private methods, but it's conventional to indicate that a method is for private use of the class by giving it a name that starts with a single leading underscore, eg _init_my_array. If a user of your class wants to call that method they can, but they know that doing so may cause the class to misbehave, and that it's generally not a good idea to call such "private" methods unless you know what you're doing.

Community
  • 1
  • 1
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182