getattr 问题

0 投票
1 回答
984 浏览
提问于 2025-04-17 10:08

我这一个小时都在抓狂,试图找出我正在开发的支持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))

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)

撰写回答