Python 在不首先创建类实例的情况下调用函数

Python 在不首先创建类实例的情况下调用函数,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 tha

可能重复:

我认为我的问题很直截了当,但更清楚地说,我只是想知道,我有:

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)
所以我希望你明白我的要求,有时候我不想创建一个实例,然后从这种函数中检索数据。因此,问题是可以这样做,还是不可以,如果可以,请告诉我如何实现这一点。

添加,然后删除
self
参数:

    @staticmethod
    def userAgentForUrl(url=None):
decorator也将为您处理实例调用案例,因此您实际上可以通过对象实例调用此方法,尽管这种做法通常不被鼓励。(静态调用静态方法,而不是通过实例。)

这称为静态方法:


当然,您不能在其中使用
self

是的,请看每个URL的用户代理是否有所不同?如果不是,为什么不将其作为类属性?
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()