【问题标题】:Call function without creating an instance of class first [duplicate]调用函数而不首先创建类的实例[重复]
【发布时间】:2012-12-12 09:00:07
【问题描述】:

可能重复:
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)

所以我希望你明白我的要求,有时我不想创建一个实例,而是从这种函数中检索数据。所以问题是有没有可能,如果有,请给我一些关于如何实现这一点的指导。

【问题讨论】:

标签: python


【解决方案1】:

这称为静态方法

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

【讨论】:

    【解决方案2】:

    添加staticmethod decorator,并删除self 参数:

        @staticmethod
        def userAgentForUrl(url=None):
    

    装饰器也会为您处理实例调用情况,因此您实际上可以通过对象实例调用此方法,尽管通常不鼓励这种做法。 (静态调用静态方法,而不是通过实例。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多