簡體   English   中英

從其他地方初始化的類中調用靜態方法

[英]Calling a static method from class initialised elsewhere

我有以下用於創建,寫入和關閉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

有人知道解決此問題的正確方法嗎? 干杯!

根據您所說的,我相信您正在尋找這樣的東西:

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的類中導入log_file即可。

剛意識到一個模塊可能是我最好的選擇,我將類更改為下面的模塊,並獲得了想要的結果

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM