zoukankan      html  css  js  c++  java
  • Python 函数参数使用

    参考来源:Magnus Lie Hetland 《Python基础教程》

    1. 自定义函数

    def hello( name ):
        return 'Hello, ' + name + '!'

    可以判断一个对象是不是函数:

    callable( hello )

    如果是函数,就会返回True,否则会返回False

    2. 文档字符串 docstring

    def square(x):
        'Calculate the square of the number x‘
        return x*x

    其中的 'Calculate the square of the number x' 成为函数的一部分,可以用成员 __doc__ 调用

    square.__doc__

    3. 修改参数:字符串、数字变量等参数调用之后不变值,列表会变值。这和C++是完全一致的。

    def try_to_change(n):
        n = 'Mr. Gumby'
    name = 'Mrs. Entity'
    try_to_change(name)
    name

    调用之后,name的值仍为 'Mrs. Entity',所以字符串参数调用之后是值不变的(对应 C++ 中的形式参数)

    def change(n):
        n[0] = 'Mr. Gumby'
    names = [ 'Mrs. Entity', 'Mrs. Thing' ]
    change(names)
    names

    会显示 [ 'Mr. Gumby', 'Mrs. Thing' ],即列表作为参数,在函数调用之后值改变。

    4. 关键字参数和默认值

    def hello_3( greeting = 'Hello', name = 'World' ):
        print( '{}, {}!'.format(greeting, name) )
    hello_3()
    hello_3('Hi', 'Johnny')
    hello_3(name = 'Ann', greeting = 'Good Morning' )

    会显示

    'Hello, World'

    'Hi, Johnny'

    'Good Morning, Ann'

    第一种是参数默认值(因为没有指定参数值),第二种是使用指定的参数,第三种是用关键字给参数,可以颠倒参数次序,并让调用语句更易读。

  • 相关阅读:
    Chap2: question: 1
    资格赛:题目3:格格取数
    资格赛:题目2:大神与三位小伙伴
    资格赛:题目1:同构
    最大流问题
    webpack(5)配置打包less和sass
    webpack(4)配置打包css
    C++进阶知识点(3)类的静态成员 字符和数字的互转 lambda
    ubuntu shell 监控某个进程占用的资源
    webpack(4)配置打包多个html
  • 原文地址:https://www.cnblogs.com/luyi07/p/14383397.html
Copyright © 2011-2022 走看看