我正在尝试根据另一个类的实例创建一个类。为此,我使用__new__
方法:
import logging
class Logger:
def __new__(cls):
logger = logging.getLogger('main')
# make a queue in a thread to put log messages in a PyQt text browser console
return logger
def close(self):
pass
# close the thread
def main():
logger = Logger()
# more things
logger.close()
if __name__ == '__main__':
main()
我收到AttributeError:
AttributeError: 'Logger' object has no attribute 'close'
我的想法是制作一个类,以包装从logging.getLogger('main')返回的实例,并能够调用其原始方法(如setLevel)并添加自己的方法。
对于我的问题,日志记录模块的使用并不是至关重要的,但这是我不知道如何在这种情况下使用子类化的一个示例。
我的问题是:
__new__
方法时如何进行这项工作?您可能应该将它们子类化:
from logging import Logger
def MyLogger(Logger):
def close(self):
pass
if __name__ == "__main__":
logger = MyLogger("some_name")
logger.close()
就是说,我不知道您为什么需要手动关闭记录器。他们将在删除对象时处理自己的关闭操作,这在退出Python时也会发生。如果您出于某种原因要半途删除它们,则可以从它们自己的结构中删除它们而没有问题。
OP在一条评论中澄清说,这旨在与PyQt5一起使用。这是过去一年来我一直在使用的东西。
用于显示日志记录的小部件:
# my_package.gui.logwidget.py
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QTextEdit
from PyQt5.QtCore import QSize
from my_package.logger import handler
class LogWidget(QTextEdit):
"""
Creates a simple textEdit widget that will automatically subscribe to the QLogger.
"""
# pylint: disable=R0903, R0201
def __init__(self, parent=None):
super().__init__(parent)
handler.recordReady.connect(self.append)
self.setReadOnly(True)
# For reasons mere mortals like me cannot imagine, to get a real Monospaced font,
# we need to set it on a font that doesn't exist.
font = QFont("MichaelMcDoesntExist")
font.setStyleHint(QFont.Monospace)
self.setFont(font)
def minimumSizeHint(self) -> QSize:
return QSize(800, 200)
实际记录器:
# my_package.logger.py
import logging
from PyQt5.QtCore import QObject, pyqtSignal
class QLogHandler(QObject, logging.Handler):
"""
QObject subclass of logging.Handler. Will emit the log messages so QObjects can listen to it to catch log
messages.
Signal:
recordReady:
Will emit a string that is the formatted log message.
"""
recordReady = pyqtSignal(str)
def emit(self, record):
self.recordReady.emit(self.format(record))
def __repr__(self):
return f"<{self.__class__.__name__} : {logging.getLevelName(self.level)}>"
handler = QLogHandler() # Global ref to connect to it's signals
Python的内置logging
模块已经支持线程安全日志记录对象,因此,要使它起作用,您需要做的就是拥有一个日志处理程序以及任意数量的日志显示小部件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句