Python 实例化期间传递到类中的参数/Kwarg被忽略
我很难理解为什么这个类对象不接受我的init参数。这是Python3.6 在一个文件中,我导入一个webcrawler并将kwargs传递到其中:Python 实例化期间传递到类中的参数/Kwarg被忽略,python,class,oop,keyword-argument,Python,Class,Oop,Keyword Argument,我很难理解为什么这个类对象不接受我的init参数。这是Python3.6 在一个文件中,我导入一个webcrawler并将kwargs传递到其中: import metacrawler as mc mc.crawlwrapper(url=archive_url, archive_org=True, index_pages=True, depth_limit=2, fileroot='content/') 调试:是的,此时True参数定义为True {'archive\u org':True}
import metacrawler as mc
mc.crawlwrapper(url=archive_url, archive_org=True, index_pages=True, depth_limit=2, fileroot='content/')
调试:是的,此时True参数定义为True
{'archive\u org':True}
它进入一个创建类实例的中间函数。以下是中间函数,它将所有内容从第一个函数解析到爬虫程序:
def crawlwrapper(**kw):
fileroot = kw.get('fileroot','')
url = kw['url']
print('DEBUG(pre):{0}'.format(kw))
depth_limit = kw.get('depth_limit',3)
confine_prefix= kw.get('confine_prefix') # use to make archive.org not follow external links
archive_org = kw.get('archive_org',False) # special urlparse rules apply
exclude=kw.get('exclude',[])
print_pov=kw.get('print_pov',False)
index_pages = kw.get('index_pages')
print('DEBUG(post): depth_limit, confine_prefix, index_pages, archive_org {0}'.format([depth_limit, confine_prefix, index_pages, archive_org]))
crawler = Crawler(url, depth_limit, confine_prefix, exclude, index_pages, print_pov, archive_org)
crawler.crawl()
以下是从crawlwrapper(*kw)函数接收kwargs的爬虫程序
:
class Crawler(object):
##BUG: for some reason, at some point, the init defaults don't get overridden when instatiated.
def __init__(self, url, depth_limit, confine=None, exclude=[], locked=True, filter_seen=True, index_pages=True, print_pov=False, archive_org=None):
print('depth_limit {0}, confine {1}, index_pages {2}, archive_org {3}'.format(depth_limit, confine, index_pages, archive_org))
调试:以下是crawler.crawl()类方法中接收到的内容:
深度限制2,限制http://www.cfu.or.ug,索引页面正确,存档组织无
请注意,achive_org从True
更改为None
为什么爬虫程序没有收到我的archive\u org=True参数?这是因为当您编写
类(a,b)
时,它会将a
和b
的值传递给该类(或函数)上定义为前两个名称的任何名称
但是当你说Class(a=a,b=b)
时,你说的是“调用Class.\uu初始化\uuu
,将a设置为a(从我的范围)
并将b
设置为b(从我的范围)
您在第一次调用中编写的内容相当于crawler=crawler(root=url,depth\u limit=depth\u limit,conmit=conmit\u前缀,exclude=exclude,locked=index\u pages,filter\u seen=print\u pov,index\u pages=archive\u org,print\u pov=False,archive\u org=None)
换句话说,调用方的命名空间/作用域与被调用函数/方法的签名之间没有隐式关系。除非使用关键字参数(a=a
),否则参数是按位置分配的
Python 3添加了对可能有助于防止这种情况的仅关键字参数的支持。如果您定义了Crawler.\uuuu init\uuuu
:
def __init__(self, root, depth_limit, *, confine=None, exclude=[], locked=True, filter_seen=True, index_pages=True, print_pov=False, archive_org=None)
*
将表示剩余参数不能按位置指定,必须用名称表示
老实说,我在这个问题上也被难住了,直到我得到了暗示