Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function without creating an instance of class first [duplicate]

Tags:

python

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.

like image 760
Vor Avatar asked Dec 26 '12 21:12

Vor


2 Answers

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.

like image 115
Pavel Anossov Avatar answered Oct 15 '22 20:10

Pavel Anossov


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

like image 20
cdhowie Avatar answered Oct 15 '22 20:10

cdhowie