• Python-14-抽象及关键字参数


    可使用内置函数callable判断某个对象是否可调用
    >>> import math
    >>> x = 1
    >>> y = math.sqrt
    >>> callable(x)
    False
    >>> callable(y)
    True
     
    用def定义函数
    def hello(name):
        return 'Hello, ' + name + '!'
    >>> print(hello('world'))
    Hello, world!
    >>> print(hello('Gumby'))
    Hello, Gumby!
     
    放在函数开头的字符串称为文档字符串(docstring) ,将作为函数的一部分存储起来
    def square(x):
        'Calculates the square of the number x.'
        return x * x
    >>> square.__doc__
    'Calculates the square of the number x.'
     
    可用内置函数help获取有关函数的信息,其中包含函数的文档字符串
    >>> help(square)
    Help on function square in module __main__:
    square(x)
    Calculates the square of the number x.
     
    有些函数什么都不返回, 什么都不返回的函数不包含return语句,或者包含return语句,但没
    有在return后面指定值。
    def test():
        print('This is printed')
        return
        print('This is not')
    >>> x = test()
    This is printed
    这里的return类似循环的break,只是跳出的是函数
    >>> x
    >>>
    >>> print(x)
    None
    所有的函数都返回值。如果你没有告诉它们该返回什么,将返回None。
     
    关键字参数:有时候,参数的排列顺序可能难以记住,尤其是参数很多时。为了简化调用工作,可指定参
    数的名称
    def hello_1(greeting, name):
        print('{}, {}!'.format(greeting, name))
    >>> hello_1(greeting='Hello', name='world')
    Hello, world!
    >>> hello_1(name='world', greeting='Hello')
    Hello, world!
    关键字参数可以指定默认值
    def hello_3(greeting='Hello', name='world'):
      print('{}, {}!'.format(greeting, name))
    >>> hello_3()
    Hello, world!
    >>> hello_3('Greetings')
    Greetings, world!
    >>> hello_3('Greetings', 'universe')
    Greetings, universe!
     
    下边的函数要求必须指定姓名,而问候语和标点是可选的
    def hello_4(name, greeting='Hello', punctuation='!'):
      print('{}, {}{}'.format(greeting, name, punctuation))
     
    >>> hello_4('Mars')
    Hello, Mars!
    >>> hello_4('Mars', 'Howdy')
    Howdy, Mars!
    >>> hello_4('Mars', 'Howdy', '...')
    Howdy, Mars...
    >>> hello_4('Mars', punctuation='.')
    Hello, Mars.
    >>> hello_4('Mars', greeting='Top of the morning to ya')
    Top of the morning to ya, Mars!
    >>> hello_4()
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: hello_4() missing 1 required positional argument: 'name'
     
    如果给参数name也指定了默认值,最后一个调用就不会引发异常。
     
     
     
  • 相关阅读:
    21.算法实战---栈
    初见Gnuplot——时间序列的描述
    MATLAB连接MySQL数据库
    用python做些有意思的事——分析QQ聊天记录——私人订制
    遇见蒙特卡洛
    层次分析模型(AHP)及其MATLAB实现
    CPP,MATLAB实现牛顿插值
    CPP&MATLAB实现拉格朗日插值法
    python3爬虫再探之豆瓣影评数据抓取
    R——启程——豆瓣影评分析
  • 原文地址:https://www.cnblogs.com/swefii/p/10887574.html
Copyright © 2020-2023  润新知