Call function without creating an instance of class first

Possible Duplicate:
Static methods in Python?

I think my question is pretty straight forward, but to be more clear I'm just wondering, i have this :

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"

and some where in a different class, that is in the same file, I want to get this user-agent.

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

I was trying to do something like this:

print MyBrowser.userAgentForUrl()

but got this error:

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

So I hope you got what I'm asking, some times I don't want to create an instance, and than retrieve the data from this kind of function. So the question is it possible to do, or no, if yes, please give me some directions on how to achieve this.


This is called a static method:

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()

Naturally, you can't use self in it.


Add the staticmethod decorator, and remove the self argument:

    @staticmethod
    def userAgentForUrl(url=None):

The decorator will take care of the instance-invoke case for you too, so you actually will be able to call this method through object instances, though this practice is generally discouraged. (Call static methods statically, not through an instance.)

链接地址: http://www.djcxy.com/p/55132.html

上一篇: 模仿静态方法

下一篇: 调用函数而不先创建类的实例