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'

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

  • 相关阅读:
    大整数模拟
    MSSQL存储过程中获取记录集并循环操作一例
    about协议的妙用
    C#基础概念二十五问
    很完美的JS判断日期函数
    asp.net C# FileUpload 控件如何判断文件名的后缀
    c++中指针学习的两个绝好例子
    ASP.net性能优化总结
    C++指针
    JS中的undefined,null,"",0和false
  • 原文地址:https://www.cnblogs.com/luyi07/p/14383397.html
Copyright © 2011-2022 走看看