如何将self传递给构造函数
考虑一下下面这个类:
class WebPageTestProcessor:
def __init__(self,url,harUrl):
self.url = url
self.harUrl = harUrl
def submitTest():
response = json.load(urllib.urlopen(url))
return response["data"]["testId"]
def main():
wptProcessor = WebPageTestProcessor("http://www.webpagetest.org/runtest.php?f=json&priority=6&url=http%3A%2F%2Fwww.target.com%2F&runs=3&video=1&web10=0&fvonly=1&mv=1&k=d3ebfa90cb4e45a9bb648e7ebf852321")
print wptProcessor.submitTest()
if __name__ =='__main__':main()
运行时,它会报错,提示:
TypeError: __init__() takes exactly 3 arguments (2 given).
我传入了 None
作为参数:
wptProcessor = WebPageTestProcessor(None,"http://www.webpagetest.org/runtest.php?f=json&priority=6&url=http%3A%2F%2Fwww.target.com%2F&runs=3&video=1&web10=0&fvonly=1&mv=1&k=d3ebfa90cb4e45a9bb648e7ebf852321")
然后它又说:
TypeError: submitTest() takes no arguments (1 given)
有没有人知道怎么把 self
传给构造函数?
2 个回答
1
self
这个词在类的所有非静态方法中会自动传递。你需要这样定义 submitTest
:
def submitTest(self):
# ^^^^
response = json.load(urllib.urlopen(self.url))
# ^^^^^
return response["data"]["testId"]
你会注意到我在 url
前面加了 self.
。这样做是因为 url
是这个类的一个实例属性(只能通过 self
来访问)。
3
你需要给WebPageTestProcessor
这个类传递两个参数,分别是url
和harUrl
。
但你现在只传了一个参数,也就是:
"http://www.webpagetest.org/runtest.php?f=json&priority=6&url=http%3A%2F%2Fwww.target.com%2F&runs=3&video=1&web10=0&fvonly=1&mv=1&k=d3ebfa90cb4e45a9bb648e7ebf852321"
这里的self变量代表的是对象本身,你可以把它改成任何你想要的名字。
问题出在你传递参数的顺序上,试试这样:
class WebPageTestProcessor(object):
def __init__(self,url,harUrl):
self.url = url
self.harUrl = harUrl
def submitTest(self):
response = json.load(urllib.urlopen(self.url))
return response["data"]["testId"]
def main():
wptProcessor = WebPageTestProcessor("http://www.webpagetest.org/runtest.php?f=json&priority=6&url=http%3A%2F%2Fwww.target.com%2F&runs=3&video=1&web10=0&fvonly=1&mv=1&k=d3ebfa90cb4e45a9bb648e7ebf852321", None)
print wptProcessor.submitTest()
if __name__ == '__main__':
main()
在上面的代码中,我们解决了三个问题:
- 将self设置为
submitTest
方法。 - 在
submitTest
方法中使用self.url
,因为它是类的一个属性。 - 通过传递两个参数来修正类的实例创建,就像我们之前声明的那样。