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也指定了默认值,最后一个调用就不会引发异常。
 
 
 
posted @ 2019-05-18 22:57  swefii  阅读(175)  评论(0编辑  收藏  举报