0

I want to make a practice with module ThreadPool,to add 2 for every element in range(1,100).

from multiprocessing.pool import ThreadPool
array=range(1,100)
class test():
    def  myadd(self,x):
        return(x+2)

do=ThreadPool(5)
do.map(test.myadd,array)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "D:\Python34\lib\multiprocessing\pool.py", line 255, in map
 return self._map_async(func, iterable, mapstar, chunksize).get()
 File "D:\Python34\lib\multiprocessing\pool.py", line 594, in get
  raise self._value
TypeError: exceptions must derive from BaseException

>>> do.map(test.myadd(self),array)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'self' is not defined
>>> do.map(test.myadd(),array)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: myadd() missing 2 required positional arguments: 'self' and 'x'

How to write the map sentence here to call array to calculate ? it is easy for me to do that with function such way:

from multiprocessing.pool import ThreadPool
array=range(1,100)
def  myadd(x):
    return(x+2)

do=ThreadPool(5)
do.map(myadd,array)

It works fine for me,when change the function into method in a class ,i am confused.

dano
  • 91,354
  • 19
  • 222
  • 219
showkey
  • 482
  • 42
  • 140
  • 295

1 Answers1

1

If you're going to make myadd an instance method of the test class, you have to actually instantiate the test class to call myadd:

from multiprocessing.pool import ThreadPool

class test():
    def myadd(self,x):
        return(x+2)

t = ThreadPool(5)
test_obj = test()  # This gives you an instance of the `test` class
t.map(test_obj.my_add, range(1,100))  # Now you can call `myadd` on your instance
dano
  • 91,354
  • 19
  • 222
  • 219
  • dano,could i send another post on the topic which is deleted? – showkey Aug 03 '14 at 02:48
  • @it_is_a_literature I'm not exactly sure what you mean. Are you asking if you can post another questoin on this topic? Also, can you clarify what you mean by "which is deleted". What got deleted? – dano Aug 03 '14 at 03:08
  • a=range(1,10) b=range(3,12) ,t.map(test_obj.myadd,a,b) ,it can't run,i have asked before in this post,and you have answered it,but you deleted all of them,you revised the answer. – showkey Aug 03 '14 at 03:12
  • @it_is_a_literature [My answer](http://stackoverflow.com/a/25072448/2073595) to that question is still there. Its at the end, after the line that says **Edit:**. – dano Aug 03 '14 at 03:15