Python: How can I call __Init__ call for two different argument methods?

I want to create an init method that can understand these contstrutors.

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

or pass into a whole dict

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

class candy:
    def __init__ ?????


How can I make the init method match like a constructor?

thanks for the help


source to share

2 answers

You can define init as usual, for example:

class candy(object):
    def __init__(self, name, type): = name
        self.type = type


and then pass arguments in both directions:

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



candy(**{ 'name': 'name', 'type': 'type' })



and the section immediately preceding it,

In your specific case, it might look something like this:

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




All Articles