0

I am a beginner in Python classes and OOP in general.

I have a class like this:

class TSP():
    cities=None

    def __init__(self):
        df = pd.read_excel('order data.xlsx')
        self.cities = df.copy()
    
    def something():
        #####Do something###########

tsp = TSP()
tsp.something()

Now instead of just simply passing an excel file, I hope to implement a loop so that my program takes a file, runs everything, then takes another file, reruns everything, and so on and so forth.

Now, I am not sure how to implement this concept inside a class. Normally, I would have just placed my whole code inside a loop to get different files and run the code, but not sure how to do it in Classes.

Artyom Vancyan
  • 5,029
  • 3
  • 12
  • 34
Bhavya Budhia
  • 115
  • 1
  • 2
  • 10
  • 1
    The assignment `cities = None` doesn't do anything useful. It defines a *class* attribute that is independent of the *instance* attribute defined inside `TSP.__init__`. – chepner Nov 17 '22 at 15:44
  • 1
    This class might be a simplified example of your real code, but a class with only one method in addition to `__init__` should probably just be a regular function. – chepner Nov 17 '22 at 15:44
  • 1
    Only you can decide of you actually need a class here (or an OOP approach in general). If all you need to do is loop over some files and do some calculations for each, that might not be the case. Anyhow, nothing is stopping you from looping over your dataframe in either the constructor or any of the class methods. See https://stackoverflow.com/questions/16476924/how-to-iterate-over-rows-in-a-dataframe-in-pandas for how. – nick Nov 17 '22 at 15:46

0 Answers0