迭代方法 - Python
iterating over methods - Python
我在 class Domain
:
中创建了以下线程实用程序
def __run_threads(self, targets):
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
future_job = { executor.submit(target): target for target in targets }
for future in concurrent.futures.as_completed(future_job):
try:
data = future.result()
except Exception as exc:
self.log.exception(exc)
else:
self.log.info("Data: %s" % data)
就是这样,我可能想要terminate
或initiate
一个节点,它属于我的classDomain
。为了使其尽可能通用,我想传递一个 targets
列表,一个要执行的 target
的数组:
targets = [ node.terminate_instance for node in self.nodes ]
或
targets = [ node.start_instance for node in new_nodes ]
self.__run_threads(targets)
但是,当我执行函数时,我得到:
test_domain.py", line 19, in test_constructor
dobj = domain.Domain(name="test_domain", cluster_size=1)
File "domain.py", line 31, in __init__
self.__run_threads(om_node.start_instance)
File "domain.py", line 71, in __run_threads
future_job = { executor.submit(target): target for target in targets }
TypeError: 'instancemethod' object is not iterable
如何遍历 Python 中的方法列表?
追溯表明您正在这样做:
self.__run_threads(om_node.start_instance)
所以您将单个方法实例传递给 __run_threads
,而不是实例方法列表,这是该方法所期望的(以及您甚至明确声明要传递给它的内容)。你只需要让调用者传递一个列表:
self.__run_threads([om_node.start_instance]) # Or a list comprehension that provides multiple instance methods, like in your examples.
我在 class Domain
:
def __run_threads(self, targets):
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
future_job = { executor.submit(target): target for target in targets }
for future in concurrent.futures.as_completed(future_job):
try:
data = future.result()
except Exception as exc:
self.log.exception(exc)
else:
self.log.info("Data: %s" % data)
就是这样,我可能想要terminate
或initiate
一个节点,它属于我的classDomain
。为了使其尽可能通用,我想传递一个 targets
列表,一个要执行的 target
的数组:
targets = [ node.terminate_instance for node in self.nodes ]
或
targets = [ node.start_instance for node in new_nodes ]
self.__run_threads(targets)
但是,当我执行函数时,我得到:
test_domain.py", line 19, in test_constructor
dobj = domain.Domain(name="test_domain", cluster_size=1)
File "domain.py", line 31, in __init__
self.__run_threads(om_node.start_instance)
File "domain.py", line 71, in __run_threads
future_job = { executor.submit(target): target for target in targets }
TypeError: 'instancemethod' object is not iterable
如何遍历 Python 中的方法列表?
追溯表明您正在这样做:
self.__run_threads(om_node.start_instance)
所以您将单个方法实例传递给 __run_threads
,而不是实例方法列表,这是该方法所期望的(以及您甚至明确声明要传递给它的内容)。你只需要让调用者传递一个列表:
self.__run_threads([om_node.start_instance]) # Or a list comprehension that provides multiple instance methods, like in your examples.