AttributeError:“函数”对象没有属性“ func_name”和python 3 [英] AttributeError: 'function' object has no attribute 'func_name' and python 3

查看:389
本文介绍了AttributeError:“函数”对象没有属性“ func_name”和python 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下载了以下代码:

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下出现以下错误:

It works fine under python 2, but I get the following error under 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下工作。 / p>

I need to work under python3.

推荐答案

由于从Python 2更改了Python 3后,这种行为有望出现。

That behaviour in Python 3 is expected as it was changed from Python 2. Per the documentation here:

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 __

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 __

You will notice the mention of func_name as one of the attributes that were renamed. You will need to use __name__.

Python 3中的示例代码:

Sample code in Python 3:

>>> def foo(a):
...  print(a.__name__)
... 
>>> def c():
...  pass
... 
>>> 
>>> foo(c)
c

这篇关于AttributeError:“函数”对象没有属性“ func_name”和python 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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