简体   繁体   中英

_args and _kwargs arguments for python

#!/usr/bin/env python


class Countries(object):
        def __init__(self,*_args,**_kwargs):
                self.name = 'japan'
                self.continent = 'asia'
                self.capital = 'tokyo'
                print _args
                print _kwargs

        def display(self):
                print self.name, self.continent,self.capital




iraq = Countries('iraq','bagdad','asia')

iraq.display()

india = Countries('india','delhi','asia')

india.display()

I have written a self teaching example above.I know that irrespective of the parameters I am always assigning

'japan' , 'asia' , 'tokyo'

to the member variables of the class.I wrote the above in an attempt to understand

   *_args and **_kwargs

The output of the above program is as below

('iraq', 'bagdad', 'asia')
{}
japan asia tokyo
('india', 'delhi', 'asia')
{}
japan asia tokyo

where _args is ('iraq', 'bagdad', 'asia')

and __kwargs is {}

why is a null string being printed for _kwargs and all arguments printed as a list for _args

Because you aren't passing in any keyword arguments. If you did Countries('Iraq', capital='Bagdad') , then it would print something for kwargs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM