Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

oop

class

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()
like image 726
user1919 Avatar asked Nov 24 '25 03:11

user1919


2 Answers

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.

like image 173
Mark Hildreth Avatar answered Nov 25 '25 17:11

Mark Hildreth


Use loops to simplify repetitive tasks.

Usually, it is a good idea to use a loop to instantiate objects, especially if they are to be stored in an array.

Further, do not worry about OOP nor optimization, focus on the intent and the requirement, and from what you said in your post, it is hard to tell why you are worrying about this.

Overall, yes, if you need many instances of a class, you should use a loop and store them in an array, however keep in mind that OOP is a means, not an objective, if it looks wrong, you need to check if it meets the requirements, as most OOP concepts are greatly misused by beginners (usually doing OOP for the sake of doing OOP does lead to issues of varying kinds).

like image 38
Dmitry Avatar answered Nov 25 '25 16:11

Dmitry