这里怎么写map语句调用array用ThreadPool模块计算? [英] How to write the map sentence here to call array to calculate with ThreadPool module?

查看:54
本文介绍了这里怎么写map语句调用array用ThreadPool模块计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用模块 ThreadPool 做一个练习,为 range(1,100) 中的每个元素添加 2.

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'

这里怎么写map语句调用array来计算?我很容易用这种方式做到这一点:

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.

推荐答案

如果你打算让 myadd 成为 test 类的实例方法,你必须实际实例化test 类来调用myadd:

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

这篇关于这里怎么写map语句调用array用ThreadPool模块计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆