2014-12-13 41 views
1

即時得到一個類型錯誤,我的課是在其功能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://stackoverflow.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://stackoverflow.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

回答

5

您需要定義pck參數。

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

,或者如果你想使參數可選的默認值來定義這樣的方法:

def dl(self,_dir,_url,pck=True): 
相關問題