2014-01-14 68 views
0

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

爲什麼你想要它是一個靜態方法?問題是在靜態方法中調用self。 –

+0

你的靜態方法使用'self';爲什麼它是一個靜態方法**如果你需要訪問'LockFile'實例的屬性? –

+0

您正試圖訪問'static method'內的'self'變量。這暗示該方法不應該是靜態的恕我直言。 –

回答

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) 
+0

考慮到您正在改變狀態,使用類比使用模型更具語義。 –

+0

你的用例究竟是什麼? –

+0

我需要寫入程序開始處定義的文件。它也必須被鎖定,並且文本必須被預先設定。 某些任意類或模塊需要能夠寫入它。我想它會非常類似於某種類型的記錄器,它會寫入一個預定義的文件 – TomSelleck

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