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

+3


source to share


2 answers


You can define init as usual, for example:

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

      

and then pass arguments in both directions:



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

      

or

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

      

+5




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

      

+3


source







All Articles