我有以下用於創建,寫入和關閉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
。
有沒有人知道正確的方式去做這件事?乾杯!
爲什麼你想要它是一個靜態方法?問題是在靜態方法中調用self。 –
你的靜態方法使用'self';爲什麼它是一個靜態方法**如果你需要訪問'LockFile'實例的屬性? –
您正試圖訪問'static method'內的'self'變量。這暗示該方法不應該是靜態的恕我直言。 –