2012-12-26 377 views
3

Possible Duplicate:
Static methods in Python?呼叫功能

我想我的問題是非常簡單的,但是更清晰,我只是想知道,我有這個:

class MyBrowser(QWebPage): 
    ''' Settings for the browser.''' 

    def __init__(self): 
     QWebPage.__init__(self) 
     pass 

    def userAgentForUrl(self, url=None): 
     ''' Returns a User Agent that will be seen by the website. ''' 
     return "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15" 

和一些在不同的類中,即在同一個文件中,我想獲取此用戶代理。

mb = MyBrowser() 
user_agent = mb.userAgentForUrl() 
print user_agent 

我試圖做這樣的事情:

print MyBrowser.userAgentForUrl() 

,但得到這個錯誤:

TypeError: unbound method userAgentForUrl() must be called with MyBrowser instance as first argument (got nothing instead) 

所以,我希望你得到了什麼我問,有時我不不想創建實例,而是從這種函數中檢索數據。所以問題是有可能做到,或者沒有,如果是的話,請給我一些關於如何實現這個目標的方向。

+4

是的,請參閱http://stackoverflow.com/questions/735975/static-methods-in-python – sinelaw

+2

用戶代理是否每個URL都不同?如果沒有,爲什麼你不把它作爲一個類的財產? – Blender

+0

@Blender是的,它會。 – Vor

回答

13

這就是所謂的靜態方法

class MyBrowser(QWebPage): 
    ''' Settings for the browser.''' 

    def __init__(self): 
     QWebPage.__init__(self) 
     pass 

    @staticmethod 
    def userAgentForUrl(url=None): 
     ''' Returns a User Agent that will be seen by the website. ''' 
     return "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.15 (KHTML, like Gecko) Chrome/24.0.1295.0 Safari/537.15" 


print MyBrowser.userAgentForUrl() 

當然,你不能用它self

+0

非常感謝! – Vor

1

添加staticmethod decorator,並刪除self說法:

@staticmethod 
    def userAgentForUrl(url=None): 

的裝飾會照顧實例調用情況下爲你,所以你其實可以通過對象實例調用此方法,儘管通常不鼓勵這種做法。 (調用靜態方法靜態,而不是通過一個實例。)

+0

非常感謝你 – Vor