TypeError:__ init __()需要4个位置参数,但是给出了5个

k4k*_*uz0 0 python

我查找了类似的问题,但大多数问题都与省略定义中的self论点有关__init__.

码:

class steamurl():

    baseurl = "http://api.steampowered.com/{0}/{1}/{2}/"

    def __init__(self, loc1, loc2, vnum, **options):
        self.loc1 = loc1
        self.loc2 = loc2
        self.vnum = vnum
        self.options = options

optionsdic = {
    'key': 'KEYHERE',
    'game_mode': 'all_pick',
    'min_players': '7'
    }

testurl = steamurl("IDOTA2Match_570", "GetMatchHistory", "v001", optionsdic)
Run Code Online (Sandbox Code Playgroud)

然而,在我向类中添加"optionsdic"之前,我的代码工作正常.添加后,我在标题中得到类型错误.我**kwargs错误地使用了作为参数吗?

Mar*_*ers 8

您需要使用**应用optionsdic作为关键字参数:

testurl = steamurl("IDOTA2Match_570", "GetMatchHistory", "v001", **optionsdic)
Run Code Online (Sandbox Code Playgroud)

否则它只是传入字典对象的另一个位置参数.

这反映了函数签名中的语法.


Bre*_*arn 7

如果要将内容optionsdic作为单独的关键字参数传递,则需要使用** 解包:

testurl = steamurl("IDOTA2Match_570", "GetMatchHistory", "v001", **optionsdic)
Run Code Online (Sandbox Code Playgroud)


Sim*_*ser 5

您应该调用使用**

testurl = steamurl("IDOTA2Match_570", "GetMatchHistory", "v001", optionsdic)
Run Code Online (Sandbox Code Playgroud)

这会将字典解包为单独的关键字参数。在__init__关键字参数将被包装成一个字典因**options