python 类型错误: dl() takes exactly 4 arguments (3 given)

标签 python class urllib

我收到类型错误,我的类在其函数 dl() 中使用了 self

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 中有 self,我做错了什么?

>>> 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)
>>>  

最佳答案

您需要定义 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):

关于 python 类型错误: dl() takes exactly 4 arguments (3 given),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27454691/

相关文章:

python - 如何测试变量是否包含 lambda?

python - 我可以在 pandas 中执行动态的行 cumsum 吗?

python - 具有两个优先级值的优先级队列

javascript - JavaScript ES6 类中的私有(private)属性

c++ - 为什么在 header 中的类声明中声明变量时会出现错误?

python - Web Scraper 无法从网站获取完整数据

python - 每秒运行 Python 函数一分钟

javascript - 绑定(bind)两个输入,以便即使其中之一被用户更改,它们也会显示相同的文本

python - ImportError : No module named error when importing urllib. 错误

python - 使用 Python 从 URL 下载图像给出损坏的结果