SoFunction
Updated on 2025-04-17

Several implementation methods for passing parameters in python

1. Position transfer parameters

The number of positions of actual participating formal parameters is consistent

def foo(a,b):  #Montactic Parameters    print(a)

if __name__ == '__main__':
    foo(1,2)   #born

2. Keyword transfer

Keyword parameter transfer refers to the use of the name of the formal parameter to determine the input parameters.

When specifying real parameters in this way, it does not need to be consistent with the formal parameter position, as long as the parameter name is written correctly

def foo(a,b):
    print(f"ayes{a},byes{b}")

if __name__ == '__main__':
    foo(b=1,a=2)



#resultayes2,byes1

3. Default parameter transfer

When calling a function, an exception will be thrown if no parameter is specified, that is, when defining the function, the default value of the formal parameter is directly specified.

In this way, when no parameters are passed in, the default value set when defining the function is directly used.

The syntax format is as follows:

def foo(a,b,c="I'm the default parameter"):
    print(f"ayes:{a},byes:{b},cyes:{c}")

if __name__ == '__main__':
    foo(b=1,a=2)

4. Variable parameter transfer (*args, **kwargs)

--It can also be called an indefinite-length parameter

  • 1.*args can receive position parameters of any length
  • 2.**kwargs can receive keyword parameters of any length
  • 3. When *args and **kwargs colleagues use *args (positional parameter) first and **kwargs (keyword) parameter behind.

Formal parameters are variable parameters

def foo(*args, **kwargs):
    print("Positional arguments:")
    print(type(args))

    for arg in args:
        print(arg)

    print("\nKeyword arguments:")
    print(type(kwargs))
    for key, value in ():
        print(key + ": " + str(value))


if __name__ == '__main__':
    a = foo(1,2,3,4,5,name = "tom",age = 18)
    help(foo())

Real parameters are variable parameters

def foo(a,b,name,age):

    print(a,b,name,age)

if __name__ == '__main__':
    a = [1,2]
    b = {"name":"tom","age":18}
    c = foo(*a,**b)


#result1 2 tom 18

Both the actual and formal parameters are variable parameters

def foo(*args, **kwargs):
    print("Positional arguments:")
    print(type(args))

    for arg in args:
        print(arg)

    print("\nKeyword arguments:")
    print(type(kwargs))
    for key, value in ():
        print(key + ": " + str(value))


if __name__ == '__main__':
    a = [1,2,3,4,5]
    b = {"name":"tom","age":18}
    a = foo(*a,**b)

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.