Forced naming of parameters in Python

后端 未结 11 1275
日久生厌
日久生厌 2020-11-27 12:15

In Python you may have a function definition:

def info(object, spacing=10, collapse=1)

which could be called in any of the following ways:<

11条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 13:08

    def cheeseshop(kind, *arguments, **keywords):
    

    in python if use *args that means you can pass n-number of positional arguments for this parameter - which will be accessed as a tuple inside the function.

    And if use **kw that means its keyword arguments, that can be access as dict - you can pass n-number of kw args, and if you want to restrict that user must enter the sequence and arguments in order then don't use * and ** - (its pythonic way to provide generic solutions for big architectures...)

    if you want to restrict your function with default values then you can check inside it

    def info(object, spacing, collapse)
      spacing = 10 if spacing is None else spacing
      collapse = 1 if collapse is None else collapse
    

提交回复
热议问题