Python学习总结18:函数 参数篇

时间:2023-12-15 14:10:50

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