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
()
{}

最新文章

  1. 十分钟了解分布式计算:Google Dataflow
  2. Linux gcc 编译日记
  3. Windows上管理远程Linux VPS/服务器文件工具 - winscp
  4. 通过发布项目到IIS上,登录访问报系统找不到System.Web.Mvc
  5. Javascript模块规范(CommonJS规范&amp;&amp;AMD规范)
  6. Hibernate详解(5)——Hibernate核心接口和工作原理
  7. Python之路--你不知道的platform
  8. Android学习笔记-绘制圆形ImageView实例
  9. Java SocketChannel 读取ByteBuffer字节的处理模型
  10. 【linux之挂载,Raid,LVM】
  11. cisco交换机实现端口聚合
  12. Cocos Creator 资源加载流程剖析【一】——cc.loader与加载管线
  13. centos 7 安装vscode
  14. 使用mpvue开发小程序
  15. host大法之GitHub上不去
  16. HNOI2017单旋
  17. .NET Core错误:The specified framework &#39;Microsoft.NETCore.App&#39;, version &#39;1.0.0-rc2-3002702&#39; was not found.
  18. 2008-03-18 22:58 oracle基础知识小结
  19. 哪些优秀的 Windows 小工具,类似 clover 或 everything
  20. js布尔值转化

热门文章

  1. [qemu] 在前端驱动使用virtio的情况下,如何让后端使用vhost-user [未解决]
  2. jquery的$.ajax async使用详解
  3. Python的深拷贝与浅拷贝
  4. hadoop 2.4 伪分布式模式
  5. ThreadLocal知识总结
  6. 【Android测试】【第九节】MonkeyRunner—— 初识
  7. js实现选项卡
  8. JS的基础类型与引用类型
  9. LeetCode Longest Palindrome
  10. 面试&amp;笔试常见题,你了解多少?