过去一小时我一直在试图弄清楚我正在研究的启用IRC的程序中的错误,经过一些调试我发现由于某种原因,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函数的第二个参数的方式不是基本相同吗?为什么会发生这种情况,以及关于如何处理这样的错误的任何想法?谢谢。
编辑:这是(简短的)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))
答案 0 :(得分:4)
不,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)