Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 380
TheOneTeam Avatar asked Mar 18 '26 15:03

TheOneTeam


1 Answers

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' })
like image 85
Chenxiong Qi Avatar answered Mar 21 '26 03:03

Chenxiong Qi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!