Kit Ho
Kit Ho

Reputation: 26968

Python: How can I make the __Init__ call for two different method of argument?

I wanna make a init method which 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 such that accommodate both constructor??

Thanks for help

Upvotes: 3

Views: 239

Answers (2)

Chenxiong Qi
Chenxiong Qi

Reputation: 426

You can define the init as normal, for example:

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

and then pass arguments in both ways:

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

or

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

Upvotes: 5

Amber
Amber

Reputation: 526583

http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists

and the section immediately preceding it,

http://docs.python.org/tutorial/controlflow.html#keyword-arguments

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

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']

Upvotes: 3

Related Questions