![](/img/trans.png)
[英]Calling a Python class method from C++, if given an initialised class as PyObject
[英]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.