1

I went through examples of function factories, but I still cannot understand something... I have a class Sample. For objects instantiated from that class, I have an attribute: a function f telling me different words (e.g. 'one' or 'two'). To do so, I create a Factory, where I define f for each sample. All samples are stored in SampleCollection class. Then, I call function f for each sample from the collection. I cannot understand why the output 'two' and 'two', and not 'one' and 'two' as I would expect...

class Sample():

    def __init__(self):
        self.f = None

    def call_f(self):
        print self.f()

class SampleCollection():

    def __init__(self):
        self.container = []

    def add(self, sample):
        self.container.append(sample)

class Factory():

    def __init__(self, collection):
        self.collection = collection

    def generate_f(self, words):

        for w in words:
            def f(): return w

            s = Sample()
            s.f = f
            self.collection.add(s)

col = SampleCollection()
fab = Factory(col)

words = ['one', 'two']
fab.generate_f(words)

for s in col.container:
    s.call_f()

UPD: Thank you for your answers! I didn't know how it is called correctly. Example solution is to change the function definition: def f(w=w): return w.

desa
  • 1,240
  • 12
  • 31

0 Answers0