Home > Backend Development > Python Tutorial > Parameter passing of python function

Parameter passing of python function

高洛峰
Release: 2016-10-19 13:49:23
Original
1875 people have browsed it

In this use case, what we are going to discuss is about the parameter passing of functions

The python version I am using is 3.3.2

For functions:

1

2

3

4

5

6

7

8

def fun(arg):

print(arg)

def main():

fun('hello,Hongten' )

​​​

if __name__ == '__main__':

main()

When we pass a parameter to the fun() function, we can print out the passed parameter value information.

The information printed here is:

hello,Hongten

For the following use case:

1

2

3

4

5

6

7

8

9

def fun(a=1, b=None, c=None, *args):

print('{0},{1},{2},{3}'.format(a, b, c, args))

                                                                                                                               . ()

When the parameters passed are: fun(a='one') and fun('one'), the value is copied to parameter a. The effect of all two parameters is the same:

one,None,None,()

one,None,None,()

Of course we can also assign values ​​to parameters: b, c, *args

such as:

1

2

3

4

5

6

7

8

def fun(a=1, b=None, c=None, *args):

print('{0},{1 },{2},{3}'.format(a, b, c, args))

​​​​​

def​main():

​​fun('one',1,2,('hongten'))

                                                                                                                                         . ('hongten',)

In the above example, we cannot bypass the parameters a, b, c in front of the parameter *args and copy them to *args:

Such as:

def fun(a=1, b=None, c=None, *args):
    print('{0},{1},{2},{3}'.format(a, b, c, args))
      
def main():
    fun(args=('hongten'))
      
if __name__ == '__main__':
    main()
Copy after login

Running effect:

Traceback (most recent call last):

File "E:/Python33/python_workspace/test_fun.py", line 21, in

main()

File "E:/Python33/python_workspace/test_fun.py", line 18, in main

fun(args=('hongten'))

TypeError: fun() got an unexpected keyword argument 'args'

But for parameters: a, b, c, you can use this Assign value in the way

such as:

def fun(a=1, b=None, c=None, *args):
    print('{0},{1},{2},{3}'.format(a, b, c, args))
      
def main():
    fun(c=('hongten'), b=2, a=[1,2,3])
      
if __name__ == '__main__':
    main()
Copy after login

Operating effect:

[1, 2, 3],2,hongten,()

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template