在实例化期间传递到类中的参数/Kwarg被忽略

2024-09-28 21:35:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难理解为什么这个类对象不接受我的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/')

DEBUG:是的,此时True参数定义为True。你知道吗

{'archive_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)函数接收kwarg的Crawler

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

调试:下面是爬虫。爬虫()类方法:

depth_limit 2, confine http://www.cfu.or.ug, index_pages True, archive_org None

注意,achive\u org从True更改为None?你知道吗

为什么Crawler没有收到我的archive\u org=True参数?你知道吗


Tags: 函数orgtrueurlgetprefixindexpages
1条回答
网友
1楼 · 发布于 2024-09-28 21:35:08

这是因为当你写Class(a, b)时,它把ab的值传递给任何被定义为类(或函数)前两个名称的名称。你知道吗

但是当你说Class(a=a, b=b)时,你说的是“呼叫Class.__init__,将a设为a (from my scope),将b设为b (from my scope)”。你知道吗

您在第一次调用中编写的内容相当于crawler = Crawler(root=url, depth_limit=depth_limit, confine=confine_prefix, exclude=exclude, locked=index_pages, filter_seen=print_pov, index_pages=archive_org, print_pov=False, archive_org=None)。你知道吗

换句话说,调用方的命名空间/作用域和被调用函数/方法的签名之间没有隐式关系。参数是按位置分配的,除非使用关键字参数(a=a)。你知道吗

python3添加了对仅关键字参数的支持,这些参数可能有助于防止这种情况。你这样定义Crawler.__init__

def __init__(self, root, depth_limit, *, confine=None, exclude=[], locked=True, filter_seen=True, index_pages=True, print_pov=False, archive_org=None)

*表示剩余的参数不能按位置指定,必须用名称表示。你知道吗

老实说,我也被这个问题难住了,直到我得到了提示。你知道吗

相关问题 更多 >