2014-01-14 29 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