• Python学习总结18:函数 参数篇


    1. 判断函数是否可调用

    >>> import math
    >>> x = 1
    >>> y = math.sqrt
    >>> callable(x)
    False
    >>> callable(y)
    True

         注意 函数callable在Python 3.0中不再可用,需要使用表达式hasattr(func,  __call)__代替。

    2. 函数(或类)解释

        1)函数注释,以"#"开头注释

        2)文档字符串,如果在函数的开头写下字符串,它就会作为函数的一部分进行存储,这称为文档字符串。

    def square(x):
        'Calculates the square of the number x'
        return x*x
    
    >>> square.__ doc__
    'Calculates the square of the number x'
    
    >>> help(square)
    Help on function square in module main:
    
    square(x)
        Calculates the square of the number x.

    3. 函数参数的传递方法

       1)按函数参数顺序传递

    def hello(greeting, name):
        return "%s,%s"%(greeting, name)
    >>> hello('Hello', 'World')
    Hello, World

        2) 使用关键字和默认值

    def hello_1(greeting = 'Hello', name = 'World'):
         print '%s, %s'%(greeting, name)
    
    >>>hello_1(name='Mei')
    Hello, Mei
    def hello_2(greeting, name = 'World'):
         print '%s, %s'%(greeting, name)
    
    >>>  hello_2('Hi')
    Hi, World

         3) 参数个数不定

    def print_params(*params):
        print params
    
    >>>print_ params('Testing')
    ('Testing',)
    >>> print_params(1, 2, 3)
    (1, 2, 3)

        从上面的例子可以看出,打印的为元组。若与普通参数联合使用

    def print_ params_2(title, *params):
        print title
        print params
    
    >>> print_params_2(’Params:’ 1, 2, 3)
    Params:
    (1, 2, 3)
    >>> print_params_2(’Nothing:’ )
    Nothing:
    ()

        但是不能处理关键字

    >>>print_params_ 2('Hmm...’,something=42)
    Traceback (most recent call last):
      File "<pyshell#60>",line 1, in?
        print_params_ 2('Hmm...‘,something=42)
    TypeError: print_params_2() got an unexpected keyword argument 'something'

        4) 参数个数不定,且能处理关键字

    def print_ params_3(**params):
        print params
    
    >>> print_params_ 3(x=1, y=2, z=3)
    {'z': 3, 'x': 1, 'y': 2}

          返回的是字典

          综上所有参数传递的方法,放在一起使用

    def print_ params_4(x, y, z=3, *pospar, **keypar):
        print x, y, z
        print pospar
        print keypar
    
    >>> print_params少(1, 2, 3,  5, 6, 7, foo=l, bar=2)
    1 2 3
    (5, 6, 7)
    {foo:1, 'bar': 2}
    >>> print_params_4(1, 2)
    1 2 3
    ()
    {}
  • 相关阅读:
    filter
    验证
    HTML5 canvas 内部元素事件响应
    canvas 椭圆
    计算2点角度
    复制pdf文字出来是乱码的一种可能的解决方案
    LaTeX Pdf to Word
    论文题录导入导出的困惑
    公式测试
    [LaTex]Visio文件转EPS文件[转]
  • 原文地址:https://www.cnblogs.com/zhuxiaohou110908/p/5752809.html
Copyright © 2020-2023  润新知