代码之家  ›  专栏  ›  技术社区  ›  PersianGulf

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

  •  0
  • PersianGulf  · 技术社区  · 5 年前

    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)
    

    它在python2下运行良好,但在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'
    

    我需要在蟒蛇下工作。

    1 回复  |  直到 4 年前
        1
  •  6
  •   idjaw    5 年前

    Python3中的这种行为是预期的,因为它是从Python2中改变的。根据此处的文档:

    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 作为已重命名的属性之一。你需要使用 .

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