zoukankan      html  css  js  c++  java
  • 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也指定了默认值,最后一个调用就不会引发异常。
     
     
     
  • 相关阅读:
    如果网站文字不让复制怎么办,谷歌浏览器
    Mac 微信双开
    git 线上一不小心拉取代码了,如何恢复
    php 验证港澳台身份证
    把照片弄成50k以内
    Gson序列化时排除字段
    实战Springboot内置Tomcat配置调优
    svg图标爽使用
    laravel的post请求分页数据
    php的isset函数相关问题
  • 原文地址:https://www.cnblogs.com/swefii/p/10887574.html
Copyright © 2011-2022 走看看