从其他地方初始化的类调用静态方法

时间:2014-01-14 16:41:37

标签: python static-methods

我有以下用于创建,写入和关闭LockFile的类。

class LockFileManager:
    def __init__(self,fname):
        """
        Create FileLock and Prepender objects.
        """
        self.fname = fname

        self.file_lock = FileLock(fname)
        self.file_lock.acquire()

        self.file_writer = Prepender(fname)

        print "LockFile: File lock and writer acquired!\n"

    @staticmethod
    def add_command(command):
        """
        Prepend a command to the LockFile
        """
        print "LockFile: Adding command: " + command + "\n"
        self.file_writer.write(command)

    def end(self):
        """
        Close and remove the LockFile
        """
        print "LockFile: Closing & Removing LockFile:\n"
        self.file_writer.close()
        self.file_lock.release()

        os.remove(self.fname)

在我的主体代码中,我会像这样初始化类:

lockfile = LockFileManager("lockfile.txt")

然后我的代码中的其他地方,我想写入文件:

LockFileManager.add_command("Write to LockFile provided at initialisation from some arbitrary point in the code ")

然后在代码主体的末尾,调用lockfile.exit()

当我尝试添加命令时,我得到NameError occurred: global name 'self' is not defined。如果self.file_writer.write(command)更改为file_writer.write(command),则它不知道file_writer是什么。

有人知道正确的方法吗?干杯!

2 个答案:

答案 0 :(得分:1)

根据你的说法,我相信你正在寻找这样的东西:

from threading import Lock

class LockFile(file):
    def __init__(self, *args, **kwargs):
        super(LockFile, self).__init__(*args, **kwargs)
        self._lock = Lock()

    def write(self, *args, **kwargs):
        with self._lock:
            super(LockFile, self).write(*args, **kwargs)

log_file = LockFile('path/to/logfile', 'w')

然后,只需在需要写入的类中导入log_file

答案 1 :(得分:0)

刚才意识到模块可能是我最好的选择,我将课程改为下面的模块,并取得了我想要的结果

def start(fname):
    """
    Create FileLock and Prepender objects.
    """
    global lockfile_name
    global file_lock
    global file_writer

    lockfile_name = fname

    file_lock = FileLock(fname)
    file_lock.acquire()

    file_writer = Prepender(fname)

    print "LockFile: File lock and writer acquired!\n"


def add_command(command):
    """
    Prepend a command to the LockFile
    """
    print "LockFile: Adding command: " + command + "\n"
    file_writer.write(command)

def end():
    """
    Close and remove the LockFile
    """
    print "LockFile: Closing & Removing LockFile:\n"
    file_writer.close()
    file_lock.release()

    os.remove(self.fname)
相关问题