Python类函数调用

时间:2012-11-23 17:21:29

标签: python class function

我有以下代码

class myclass(object):
    def __init__(self):
        self._fileA = os.path.join(dir, file)
        self._stuffA = 'NONE'

    def log(self, message):
        # Checks if the log file exists and if not creates a new one. 
        # Attempts to open the log file. If it cannot it raises an error
        try:
            log_file = open(self._fileA, 'ab')
        except IOError, e:
            print "!!! ERROR !!! - " + str(e)
            return 0

        now = datetime.datetime.now()
        # Sets up the date and the log file entry
        message = now.strftime("%Y-%m-%d %H:%M:%S") + ' - ' + str(message)
        # Writes the log entry then places a newline and closes the log file.
        log_file.write(logmsg)
        log_file.write('\n')
        log_file.close()

    def cleanup(self):
        logmsg = '----- ENDED SEARCH -----'
        self.log(logmsg)

现在这只是我遗漏了很多内容的片段。但是当从我的类中调用日志函数时。它只是将最后一条消息写入文件副,即从清理功能发送给它的新文件。关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:1)

您将logmsg写入文件,但从未在您的函数中定义它:

    log_file.write(logmsg)

您必须使用正在使用的logmsg全局。

您的实际消息变量名为message,请改为编写:

    log_file.write(message)