Python:如何对两种不同的参数方法进行_Init__调用?

Python:如何对两种不同的参数方法进行_Init__调用?,python,constructor,Python,Constructor,我想做一个init方法,可以理解这些接触器 candy(name="foo", type="bar") or pass into a whole dict candy({"name":"foo" , "type":"bar"}) class candy: def __init__ ????? 如何使init方法同时容纳两个构造函数 谢谢你的帮助 以及紧接该条之前的条文 在您的特定情况下,它可能看起来像这样: def __init__(*args, **kwargs):

我想做一个init方法,可以理解这些接触器

candy(name="foo", type="bar")

or pass into a whole dict

candy({"name":"foo" , "type":"bar"})

class candy:
    def __init__ ?????
如何使init方法同时容纳两个构造函数

谢谢你的帮助

以及紧接该条之前的条文

在您的特定情况下,它可能看起来像这样:

def __init__(*args, **kwargs):
    if args:
        d = args[0]
        self.name = d['name']
        self.type = d['type']
    else:
        self.name = kwargs['name']
        self.type = kwargs['type']

您可以将init定义为正常,例如:

class candy(object):
    def __init__(self, name, type):
        self.name = name
        self.type = type
然后以两种方式传递参数:

candy(name='name', type='type')


你知道参数解包吗?我想我可以使用**kwargs,*args,但不完全了解它们是如何工作的。在将dict传递到函数中时,它是一个“位置参数”吗?不。它将解包成关键字args,可以是任何顺序。对于关键字args,可以是两种格式,一种是字典,另一种是“type='abc',name='jdi'”,对吗?如果有很多参数?我能不能不只是硬卡德,name type?如果
args
('name','type')
['name','type']
之类的,当然可以。
candy(**{ 'name': 'name', 'type': 'type' })