What is the purpose and use of **kwargs?

前端 未结 13 2223
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 04:59

What are the uses for **kwargs in Python?

I know you can do an objects.filter on a table and pass in a **kwargs argument. &nbs

13条回答
  •  伪装坚强ぢ
    2020-11-21 05:49

    In Java, you use constructors to overload classes and allow for multiple input parameters. In python, you can use kwargs to provide similar behavior.

    java example: https://beginnersbook.com/2013/05/constructor-overloading/

    python example:

    class Robot():
        # name is an arg and color is a kwarg
        def __init__(self,name, color='red'):
            self.name = name
            self.color = color
    
    red_robot = Robot('Bob')
    blue_robot = Robot('Bob', color='blue')
    
    print("I am a {color} robot named {name}.".format(color=red_robot.color, name=red_robot.name))
    print("I am a {color} robot named {name}.".format(color=blue_robot.color, name=blue_robot.name))
    
    >>> I am a red robot named Bob.
    >>> I am a blue robot named Bob.
    

    just another way to think about it.

提交回复
热议问题