在过去的一个小时里,我一直在努力找出我正在处理的支持IRC的程序中的一个bug,经过一些调试后,我发现由于某种原因,getattr不能正常工作。我有以下测试代码:
def privmsg(self, user, channel, msg):
#Callback for when the user receives a PRVMSG.
prvmsgText = textFormatter(msg,
self.factory.mainWindowInstance.ui.testWidget.ui.channelBrowser,
QColor(255, 0, 0, 127), 'testFont', 12)
prvmsgText.formattedTextAppend() 一切都运行得很完美。
替换以下代码,代码将中断(不会将文本输出到PyQT TextBrowser实例)
def privmsg(self, user, channel, msg):
#Callback for when the user receives a PRVMSG.
prvmsgText = textFormatter(msg,
getattr(self.factory.mainWindowInstance.ui, 'testWidget.ui.channelBrowser'),
QColor(255, 0, 0, 127), 'testFont', 12)
prvmsgText.formattedTextAppend() 这两种编写textFormatter函数第二个参数的方法本质上不是相同的吗?为什么会发生这种情况,以及关于如何处理这样的bug的任何想法?谢谢。
编辑:这里是(简要的) textFormatter类,如果它有帮助的话:
from timeStamp import timeStamp
class textFormatter(object):
'''
Formats text for output to the tab widget text browser.
'''
def __init__(self,text,textBrowserInstance,textColor,textFont,textSize):
self.text = text
self.textBrowserInstance = textBrowserInstance
self.textColor = textColor
self.textFont = textFont
self.textSize = textSize
def formattedTextAppend(self):
timestamp = timeStamp()
self.textBrowserInstance.setTextColor(self.textColor)
self.textBrowserInstance.setFontPointSize(self.textSize)
self.textBrowserInstance.append(unicode(timestamp.stamp()) + unicode(self.text))发布于 2012-01-13 06:30:22
不,getattr将获取对象的属性。它不能遍历字符串中给出的层次结构。正确的方法应该是:
getattr(self.factory.mainWindowInstance.ui.testWidget.ui, 'channelBrowser'),
QColor(255, 0, 0, 127), 'testFont', 12)或
getattr(getattr(self.factory.mainWindowInstance.ui.testWidget, 'ui'), 'channelBrowser'),
QColor(255, 0, 0, 127), 'testFont', 12)https://stackoverflow.com/questions/8843232
复制相似问题