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

标签 python

<分区>

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)

所以我希望您能理解我的要求,有时我不想创建一个实例,也不想从这种函数中检索数据。所以问题是可以做还是不可以,如果可以,请给我一些关于如何实现这一目标的指导。

最佳答案

这称为静态方法:

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

关于python - 调用函数而不先创建类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14046745/

相关文章:

python - 在 Python 中哪里使用 decimal.ROUND_05UP?

python - 编码错误: 'QuerySet' object has no attribute '_prefetch_related_lookups'

python - 字典的排序列表---默认行为是什么(没有关键参数)?

python - 从图片 url 下载图片

python - 可以从 Python 列表理解中捕获返回值以使用条件吗?

python - Pandas 到多个字典对象

python - Lektor 插件开发

python - 我如何在 API 和工作人员中使用具有不同代码库的 celery

python - 精确拆分句子

python pandas resample 应用 bin 开始和 bin 宽度