我有以下用于创建,写入和关闭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'变量。这暗示该方法不应该是静态的恕我直言。 –