Is it programmatically correct to instantiate a class inside a loop or an if statement?

class, oop, python

Solution

Creating an object in a loop is absolutely fine.

Depending on the speed of the platform that you're running on, and the actual program you're writing, this might be something to watch out for, since the instantiation of an object might be a "costly" operation. However, the "cost" is actually very minimal, and to start changing your code for this would be a classic example of "premature optimization".

Write the code the way that makes sense to you. Once your project is done, if it's running slower than what you'd like, you can profile and find what's causing it to run slow. Typically, this is I/O (database calls, reading/writing to the hard drive or network, etc.) rather than object instantiation.

Problem

Based on the following Python snippet code I want to ask if it is a good tactic to create an instance of a class inside a loop or an if statement. I am new in the concept of OOP and although I understand it in a good extent I don't know if something like this is programmatically accepted and correct. Some fellow programmer advised me, I should never instantiate a class in a loop. How something like this would affect the efficiency and the memory of my program? What is your opinion? ``` station = ['one','two'...] for station in stations_names: f = open('respond.txt','r') ## Instantiate class: ClassXmlString xmlStr = ClassXML.XML(f,station) stations_arr = xmlStr.xmlToString() ```

Original source