AttributeError:'function'对象没有属性'func_name'和pythn3

问题描述 投票:0回答:1

我下载了以下代码:

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 python-3.x function callback python-2.x
1个回答
2
投票

由于从Python 2更改了Python 3中的预期行为,请按照此处的文档进行:

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

名为func_X的函数属性已被重命名为使用__X__格式,从而在函数属性名称空间中为用户定义的属性释放了这些名称。例如,func_closure,func_code,func_defaults,func_dict,func_doc,func_globals,func_name分别重命名为__closure____code____defaults____dict____doc____globals____name__。 >

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

Python 3中的示例代码:

>>> def foo(a):
...  print(a.__name__)
... 
>>> def c():
...  pass
... 
>>> 
>>> foo(c)
c
© www.soinside.com 2019 - 2024. All rights reserved.