蟒蛇类型错误:DL()到底需要4个参数(3给出)

问题描述:

即时得到一个类型错误,我的课是在其功能DL()蟒蛇类型错误:DL()到底需要4个参数(3给出)

import urllib 
import httplib 
import os.path 

###SAI22 Library### 



def exists(site): 
    conn = httplib.HTTPConnection(site) 
    conn.request("HEAD",site) 
    response = conn.getresponse() 
    conn.close() 
    return response.status == 200 

class sai_download: 
    def dl(self,_dir,_url,pck): 
     if pck == True: 
      if exists(_url) == True: 
       urllib.urlretrieve(_url,_dir) 
       if os.path.isfile(_dir) == True: 
        print "Download successful" 
        return True 
       else: 
        print "Download failed" 
        return False 
      else: 
       print "Url isnt valid" 
       return False 


     elif pck == False: 
      if exists(_url) == True: 
       urllib.urlretrieve(_url,_dir) 
       return True 
       if os.path.isfile(_dir) == True: 
        return True 
       else: 
        return False 
      else: 
       return False 

当跑我得到的类型错误,但我用自在课堂上有自己的功能dl,我做错了什么?

>>> s = sai_download() 
>>> s.dl("C:\hh.html","http://*.com/questions/82831/check-if-a-file-exists-using-python") 

Traceback (most recent call last): 
    File "<pyshell#41>", line 1, in <module> 
    s.dl("C:\hh.html","http://*.com/questions/82831/check-if-a-file-exists-using-python") 
TypeError: dl() takes exactly 4 arguments (3 given) 
>>> 
+0

作为一个侧面说明,所有的'== TRUE'比较是不必要的;只要使用'if exists(_url):'。或者,在最后一个例子中,只是'return os.path.isfile(_dir)'。 – abarnert 2014-12-13 02:12:55

+0

另外,将所有参数命名为带下划线前缀的“私有”变量是非常奇怪的。只有'def dl(self,dir,url,pck)有什么问题:'?它看起来像是借用了一种为其他语言(也许是隐含的'self',或者JS风格的隐式全局变体)制作的习语,这在Python中不合适,并且使得代码变得不可读。 – abarnert 2014-12-13 02:13:41

+0

PS,在缩进块之前需要一个空行将其格式化为代码。 (我已经为你解决了这个问题,但为了将来的参考...) – abarnert 2014-12-13 02:14:04

您需要定义pck参数。

s.dl("C:\hh.html","http://*.com/questions/82831/check-if-a-file-exists-using-python", True) 

,或者如果你想使参数可选的默认值来定义这样的方法:

def dl(self,_dir,_url,pck=True):