您的位置:首页 > 编程语言 > Python开发

Python基础——函数

2016-08-02 21:49 302 查看

函数定义

函数的定义:
#
# Define a function.
#
def hello():
print "Hello World."

if __name__ == "__main__":
hello()
函数定义之后的下一行可以定义一个说明,通过__doc__来访问,这个跟class定义的时候一样。
函数本身也算是一个对象,除了__doc__,还定义了很多的属性。
上面的函数hello()没有返回值,默认就是None。
下面是修改后的:
#
# Define a function.
#
def hello():
'This is a function'
print "Hello World."

if __name__ == "__main__":
print dir(hello)
print hello
print hello()
print hello.__doc__
其结果如下:
['__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']
<function hello at 0x0000000004E62F28>
Hello World.
None
This is a function
第一行打印的是函数的属性;
第二行表示函数对象的位置;
第三行是函数的执行结果,第四行跟第三行通过同一个print输出,返回的值是None;
第五行打印函数的说明。

Python中的函数可以向后引用,即一个函数还没有被定义之间就可以在另外一个函数中使用:
def func3(*params):
print type(params)
func4()

def func4(**params):
print type(params)

if __name__ == "__main__":
func3()
func3()中调用了func4(),但是实际上func4()还没有定义。
但是实际上使用的时候已经有定义了func4()。

函数的返回

函数可以没有返回值,这个时候其实返回的就是None。

函数可以返回一个对象:
def ret():
return 1

if __name__ == "__main__":
r = ret()
print type(r)
这个例子中就是返回一个整型,打印结果如下:
<type 'int'>


函数一次可以返回多个值,其实就是一个元组(Tuple):
def ret():
return (1, 2)

if __name__ == "__main__":
r = ret()
print type(r)
打印的结果:
<type 'tuple'>
上面的函数中的return可以不用():
def ret():
return 1, 2, [1, 2]

if __name__ == "__main__":
r = ret()
print type(r)
而且返回的多个值的类型也没有限制。

函数的参数

首先需要说的事情是Python中的函数不能重载。
所以两个函数不能同名。
这也是因为函数参数和返回值没有类型。

函数参数可以特别指定:
def func1(x, y):
print "x = %d, y = %d" % (x, y)

if __name__ == "__main__":
func1(y = 2, x = 1)


函数参数可以带默认参数:
def func2(x = 1):
print "x = %d" % x

if __name__ == "__main__":
func2()


函数可以带不定参数,通过一个*来指定:
def func3(*params):
print params

if __name__ == "__main__":
func3()
func3(1)
func3(1, 2)
func3(1, 2, [1, 2])
返回的结果:
()
(1,)
(1, 2)
(1, 2, [1, 2])
这里的param被当成是一个元组:
def func3(*params):
print type(params)
打印的结果是<type 'tuple'>。

函数参数还可以带两个**,这时后面的参数就是一个字典类型:
def func4(**params):
print type(params)

if __name__ == "__main__":
func4()
打印的结果是<type 'dict'>。

匿名函数

Python中使用lambda关键字来定义匿名函数,方式如下:

lambda arg1,arg2... : expression
参数其实也可以没有。
下面是一个例子:
if __name__ == "__main__":
a = lambda x:x * x
print a(3)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python