2012-01-12 20 views
0

在過去的一個小時裏,我一直在試圖弄清楚我正在開發的支持IRC的程序中的一個錯誤,經過一些調試後,我發現由於某種原因,getattr工作不正常。我有以下測試代碼: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

'self.factory.mainWindowInstance.ui.testWidget.ui.channelBrowser'夥計,跆拳道?這不是Java。 – 2012-01-12 22:32:53

+0

@Samus_在PyQT中存在這種小部件的層次結構,似乎它們的屬性必須以類似的方式訪問;如果我有一個帶有UI的主窗口實例,並且在主窗口中有一堆帶有自己UI的小部件,並且_those_中有對象,則需要某種方法來引用您想要特定的對象。也許有更好的方法來做到這一點,但我仍然在學習PyQT,所以也許我還沒有找到它! – Bitrex 2012-01-12 22:48:15

回答

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) 
+0

啊,好的。所以如果我想做一個層次結構,我想我必須迭代getattr。謝謝。 – Bitrex 2012-01-12 22:35:23

+0

你爲什麼要這樣做?我想不出一個用例,這將是在Python中進行某些操作的正確方法。 – Aphex 2012-01-12 22:44:09