Search code examples
pythonargumentsdefaultnamed

Named and default arguments class arguments in Python


In PHP, I have to pass the arguments in the same order as the arguments are in the constructor.

Now, in Python, take

listbox = Listbox(root, yscrollcommand=scrollbar.set)

for example.

If I had passed yscrollcommand=scrollbar.set as the third argument and yscrollcommand was the second argument in the constructor, would I still be able to access scrollbar.set from yscrollcommand inside the listbox constructor?

I ask this because even though the arguments are not in the same order, with an equal sign they have a name.


Solution

  • Named arguments don't have to be in order.

    class xyz:
        def __init__ (self, a='1', b='2'):
            print a,b
    
    xyz(b=3,a=4)
    xyz(a=5,b=6)
    
    >>4 3
    >>5 6