在Python中,如果你尝试调用一个函数,但该函数没有被定义,你可能会遇到“AttributeError: function object has no attribute”错误。这通常是由于以下原因之一:
2、解决方案
要解决此错误,请检查以下内容:
确保你正确地拼写了函数名。确保你正在尝试调用一个存在的函数。确保你正在从一个具有该函数的对象中调用该函数。在本文中,我们将通过一个具体的例子来演示如何解决此错误。
代码例子
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 namet1 = FuncThread(datapaths, "103.0.1.40", "datapaths.log")t1.start()t1.join()
在这个例子中,我们试图从一个函数datapaths
中调用另一个函数listDatapaths
。但是,datapaths
函数没有定义listDatapaths
函数。因此,我们得到了“AttributeError: function object has no attribute”错误。
要解决此错误,我们可以将listDatapaths
函数作为参数传递给datapaths
函数。这样,datapaths
函数就可以调用listDatapaths
函数了。
修改后的代码如下:
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, listDatapaths): #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) = 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 namedef listDatapaths(mylib): return mylib.listDatapaths()t1 = FuncThread(datapaths, "103.0.1.40", "datapaths.log",listDatapaths)t1.start()t1.join()
现在,这段代码应该可以正常运行了。