调用函数而不先创建类的实例

Vor*_*Vor 4 python

可能重复:
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"
Run Code Online (Sandbox Code Playgroud)

以及在同一个文件中的某个地方,我希望得到这个用户代理.

mb = MyBrowser()
user_agent = mb.userAgentForUrl()
print user_agent
Run Code Online (Sandbox Code Playgroud)

我试图做这样的事情:

print MyBrowser.userAgentForUrl()
Run Code Online (Sandbox Code Playgroud)

但得到了这个错误:

TypeError: unbound method userAgentForUrl() must be called with MyBrowser instance as first argument (got nothing instead)
Run Code Online (Sandbox Code Playgroud)

所以我希望你得到我所要求的东西,有时候我不想创建一个实例,而是从这种函数中检索数据.所以问题是可以做或不做,如果是,请给我一些指导如何实现这一目标.

Pav*_*sov 16

这称为静态方法:

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()
Run Code Online (Sandbox Code Playgroud)

当然,你不能使用self它.