【发布时间】:2020-05-23 06:25:16
【问题描述】:
我下载了以下代码:
from __future__ import print_function
from time import sleep
def callback_a(i, result):
print("Items processed: {}. Running result: {}.".format(i, result))
def square(i):
return i * i
def processor(process, times, report_interval, callback):
print("Entered processor(): times = {}, report_interval = {}, callback = {}".format(
times, report_interval, callback.func_name))
# Can also use callback.__name__ instead of callback.func_name in line above.
result = 0
print("Processing data ...")
for i in range(1, times + 1):
result += process(i)
sleep(1)
if i % report_interval == 0:
# This is the call to the callback function
# that was passed to this function.
callback(i, result)
processor(square, 20, 5, callback_a)
在python 2下可以正常工作,但是在python3下出现如下错误:
Traceback (most recent call last):
File "test/python/cb_demo.py", line 33, in <module>
processor(square, 20, 5, callback_a)
File "test/python/cb_demo.py", line 21, in processor
times, report_interval, callback.func_name))
AttributeError: 'function' object has no attribute 'func_name'
我需要在python3下工作。
【问题讨论】:
-
您在寻找
callback.__name__??老实说,如果你只是要打印它,你还不如打印callback... -
成功了,谢谢
标签: python python-3.x function callback python-2.x