Reputation: 26968
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
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
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