声明:转载自伯乐在线
Python
中的函数,无论是命名函数,还是匿名函数,都是语句和表达式的集合。在Python
中,函数是第一个类对象,这意味着函数的用法并没有限制。Python
函数的使用方式就像Python
中其他值一样,例如字符串和数字等。Python
函数拥有一些属性,通过使用Python
内置函数dir
就能查看这些属性,如下代码所示:
def square(x):
return x**2
>>> square
<function square at 0x031AA230>
>>> dir(square)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']
>>>
其中,一些重要的函数属性包括以下几个:
doc返回指定函数的文档字符串。
def square(x):
"""return square of given number"""
return x**2
>>> square.__doc__
'return square of given number'
name返回函数名字。
def square(x):
"""return square of given number"""
return x**2
>>> square.func_name
'square'
module返回函数定义所在模块的名字。
def square(x):
"""return square of given number"""
return x**2
>>> square.__module__
'__main__'
func_defaults返回一个包含默认参数值的元组,默认参数将在后文进行讨论。
func_globals返回一个包含函数全局变量的字典引用。
def square(x):
"""return square of given number"""
return x**2
>>> square.func_globals
{
'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'square': <function square at 0x10f099c08>, '__doc__': None, '__package__': None}
func_dict返回支持任意函数属性的命名空间。
def square(x):
"""return square of given number"""
return x**2
>>> square.func_dict
{}
func_closure返回一个胞体元组,其中胞体包含了函数自由变量的绑定,闭包将在后文讨论。
函数可以作为参数传递给其他函数。这些以其他函数作为