【问题标题】:Attribute error: function object has no attribute in python属性错误:函数对象在python中没有属性
【发布时间】:2013-09-12 00:13:18
【问题描述】:

这是我调用函数 10 次并测量时间的代码

    import threading
    import logging, logging.handlers
    import hpclib
    import json
    import time
    from datetime import datetime
    from features import *


    class FuncThread(threading.Thread):
        def __init__(self, target, *args):
            self._target = target
            self._args = args
            threading.Thread.__init__(self)

        def run(self):
            self._target(*self._args)

    def datapaths(ipaddress, testlogfile):
        #initialize logging system
        testlogger = logging.getLogger("testlogger")
        testlogger.setLevel(logging.DEBUG)
        file = open(testlogfile,'w')
        file.close()
        # This handler writes everything to a file.
        h1 = logging.FileHandler(testlogfile)
        f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
        h1.setFormatter(f)
        h1.setLevel(logging.DEBUG)
        testlogger.addHandler(h1)
        mylib = hpclib.hpclib(ipaddress)
        for i in range(10):
            t1=datetime.now().time()
            (code, val) = datapaths.listDatapaths(mylib)
            t2=datetime.now().time()
            diff=t2-t1
            logger.debug('RETURN code: ', code)
            logger.debug('Time taken in seconds: ',diff.seconds)

        testlogger.removeHandler(h1)

    # Passing ipaddress of controller and log file name
    t1 = FuncThread(datapaths, "103.0.1.40", "datapaths.log")
    t1.start()
    t1.join()

当我尝试在线程中调用函数时运行此代码时出现属性错误。 这是我得到的错误。 请帮我修复。

Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
    self.run()
  File "code.py", line 17, in run
    self._target(*self._args)
  File "code.py", line 34, in datapaths
    (code, val) = datapaths.listDatapaths(mylib)
AttributeError: 'function' object has no attribute 'listDatapaths'

【问题讨论】:

  • 不要访问该对象的该属性。 “+15 代表”
  • 你希望datapaths.listDatapaths做什么?
  • datapaths 显然是一个函数——事实上,它与你正在使用的函数相同。您还没有在代码中的任何位置向它或其他任何东西添加listDatapaths 属性。它显然不是您期望所有东西都具有的标准内置属性之一。那么……除了提出 AttributeError 之外,您还期望这样做吗?
  • 另外,是什么让您认为这个问题与线程、日志记录或您正在做的任何其他事情有关?如果你不认为它有,把它去掉并发布一个更简单的SSCCE,并且不要添加一堆不相关的标签。
  • 对了,你为什么要编写自己的代码来调用一个函数 10 次并测量时间?这就是timeit 的用途,我很确定time 的文档甚至直接说“不要将它用于计时代码,在某处使用timeit

标签: python multithreading logging attributes


【解决方案1】:

只是为了得到这个答案:

def datapaths(ipaddress, testlogfile):
        # Unecessary code reomved
        (code, val) = datapaths.listDatapaths(mylib)
        # Unecessary code reomved

您正在尝试访问已定义但很可能未设置的函数的属性。我认为您需要重新检查您的代码。

【讨论】:

    猜你喜欢
    • 2014-05-14
    • 1970-01-01
    • 2020-04-01
    • 2014-07-08
    • 2019-10-23
    • 2020-05-25
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多