Python 调用函数而不先创建类的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14046745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call function without creating an instance of class first
提问by Vor
Possible Duplicate:
Static methods in Python?
可能的重复:
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.
所以我希望你明白我的要求,有时我不想创建一个实例,而不是从这种函数中检索数据。所以问题是可以做,或者不可以,如果是,请给我一些关于如何实现这一目标的指导。
采纳答案by Pavel Anossov
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 selfin it.
自然不能self在里面使用。
回答by cdhowie
Add the staticmethoddecorator, and remove the selfargument:
添加staticmethod装饰器,并删除self参数:
@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.)
装饰器也会为您处理实例调用情况,因此您实际上可以通过对象实例调用此方法,尽管通常不鼓励这种做法。(静态调用静态方法,而不是通过实例。)

