gpt4 book ai didi

python - 属性错误 : 'function' object has no attribute 'func_name' and python 3

转载 作者:行者123 更新时间:2023-12-03 16:02:59 28 4
gpt4 key购买 nike

我下载了以下代码:

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下工作。

最佳答案

Python 3 中的这种行为是预期的,因为它是从 Python 2 更改的。根据此处的文档:

https://docs.python.org/3/whatsnew/3.0.html#operators-and-special-methods

The function attributes named func_X have been renamed to use the __X__ form, freeing up these names in the function attribute namespace for user-defined attributes. To wit, func_closure, func_code, func_defaults, func_dict, func_doc, func_globals, func_name were renamed to __closure__, __code__, __defaults__, __dict__, __doc__, __globals__, __name__, respectively.



您会注意到 func_name 的提及作为重命名的属性之一。您将需要使用 __name__ .

Python 3 中的示例代码:
>>> def foo(a):
... print(a.__name__)
...
>>> def c():
... pass
...
>>>
>>> foo(c)
c

关于python - 属性错误 : 'function' object has no attribute 'func_name' and python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60107982/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com