0

在过去的一个小时里,我一直在努力找出我正在处理的支持 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))
4

1 回答 1

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)
于 2012-01-12T22:30:21.690 回答