简体   繁体   中英

Creating a new object every time you call a function in python

I have a recommender system that I need to train, and I included the entire training procedure inside a function:

def train_model(data):
  model = Recommender() 
  Recommender.train(data)
  pred = Recommender.predict(data)
  return pred

something like this. Now if I want to train this inside a loop, for different datasets, like:

preds_list = []
data_list = [dataset1, dataset2, dataset3...]
for data_subset in data_list:
  preds = train_model(data_subset)
  preds_list += [preds]

How can I make sure that every time I call the train_model function, a brand new instance of a recommender is created, not an old one, trained on the previous dataset?

You are already creating a new instance everytime you execute train_model . The thing you are not using the new instance. You probably meant:

def train_model(data):
  model = Recommender() 
  model.train(data)
  pred = model.predict(data)
  return pred

Use the instance you've instantiated, not the class

    class Recommender:
        def __init__(self):
            self.id = self

        def train(self, data):
            return data

        def predict(self, data):
            return data + str(self.id)


    def train_model(data):
      model = Recommender() 
      model.train(data)
      return model.predict(data)

    data = 'a data '
    x = {}
    for i in range(3):
        x[i] = train_model(data)
        print(x[i])

    # a data <__main__.Recommender object at 0x11cefcd10>
    # a data <__main__.Recommender object at 0x11e0471d0>
    # a data <__main__.Recommender object at 0x11a064d50>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM