Append methods in a list - Python

1

I tried to add 4 methods in a list (methodList):

def setVar(self, number):
    self.var = number

methodList = list()

for y in range(4):
    methodList.append(setVar(self, y))

and the function does not work:

>>> self.var = 0
>>> methodList[1]
>>> print(self.var)
0

If it works it would look like this:

>>> self.var = 0
>>> methodList[1]
>>> print(self.var)
1

Then I started the function to see:

>>> print(methodList[1])
None

Where did I go wrong?

    
asked by anonymous 18.09.2015 / 21:12

2 answers

2

Your function does not print anything. So it does not return anything in print .

I made some corrections:

def setVar(number):
    var = number
    return var

methodList = list()

for y in range(4):
    methodList.append(setVar(y))

print(methodList[1])

You do not need to use self for your example because you did not specify a class.

See it working here .

    
18.09.2015 / 21:20
3

If you want to set some arguments of a method (as your list calls methodList , I imagine you want to save methods, not values), you can use functools.partial . In it you establish a fixed number of arguments, and get back a "partial function":

def setVar(self, number):
    self.var = number

methodList = list()

for y in range(4):
    methodList.append(functools.partial(setVar, self, y))

self.var = 0
methodList[1]() # self.var agora deve ser 1
    
18.09.2015 / 21:32