Home  >  Article  >  Backend Development  >  Python中的自定义函数学习笔记

Python中的自定义函数学习笔记

WBOY
WBOYOriginal
2016-06-06 11:33:021590browse

定义一个什么都不做的函数

代码如下:


>>> def a():
... pass
...

>>> def printHello():
... print("hello")
...
>>> printHello()
hello
>>> callable(printHello)
True


顾名思义,callable函数用于判断函数是否可以调用;

有书上说,callable在Python3.0中已经不再使用,而使用hasattr(func, '__call__')代替;

代码如下:


>>> hasattr(printHello, '__call__')
True
  
>>> printHello.__doc__
>>> def printHello():
... 'just print hello'
... print('hello')
...
>>> printHello.__doc__
'just print hello'

  
每个函数都有一个__doc__属性,双下划线表示它是个特殊属性;
  
内建的help函数非常有用,可以提供有关方法/函数的帮助信息;

代码如下:


>>> help(printHello)

函数的注释信息包含其中;
  
虽然printHello函数没有使用return,可以用一个变量接收返回值:

代码如下:


>>> result = printHello()
hello
>>> result
>>> print(result)
None

 
None是Python的内建值,类似Javascript的undefined么?
  
定义一个可以接收参数的printStr,用以打印字符串

代码如下:


>>> def printStr(str):
... print(str)

  
>>> printStr("hello")
hello

  
像C++一样,Python支持默认参数

代码如下:


>>> def printStr(str="nothing"):
... print(str)
..
  
>>> printStr()
nothing


再来看看传参方式

代码如下:


>>> a = [1,2]
>>> def try_change_list(a):
... a[:] = [1,1,1]
...
>>> try_change_list(a)
>>> a
[1, 1, 1]


Python的传参可以理解为按值传递(同java,Javascript)?
  
BTW:如果不想让try_change_list改变原来的对象,可以传入a[:]

代码如下:


>>> a = [1,2]
>>> try_change_list(a[:])
>>> a
[1, 2]


当然,这里做的是浅拷贝,可以使用copy模块的deepcopy来进行深拷贝;
  
除了支持参数默认值,还支持命名传参:

代码如下:


>>> def sum(a=0, b=0):
... return a + b;
...
>>> sum(2,2)
4
>>> sum(b = 3, a = 4)
7


这种特性在参数较多时比较好用;
  
来看一下,Python对可变参数列表的支持:

代码如下:


>>> def sum(*args):
... s = 0;
... for i in args:
... s += i;
... return s
...
>>> sum(1,2,3,4)
10


这是一个简单的求和例子,不同于C/C++的静态类型,Python并不会限制传入sum函数的参数的类型:

代码如下:


>>> def printArs(*args):
... for a in args:
... print(a)
...
>>> printArs(2, 3, [2,2], (2,), 'df')
2
3
[2, 2]
(2,)
df
>>> printArs(*(2, 3, [2,2], (2,), 'df'))
2
3
[2, 2]
(2,)
df
>>> printArs(*[2, 3, [2,2], (2,), 'df'])
2
3
[2, 2]
(2,)
df


这里的args对应于Javascript的arguments;
  
除了使用使用元组(tuple)接收可变参数,还可以使用dictionary接收命名参数:

代码如下:


>>> def printArs(**args):
... for k in args:
... print(repr(k) + " = " + repr(args[k]))
...
>>>
>>> printArs(name='wyj', age=24)
'name' = 'wyj'
'age' = 24
>>> printArs(**{'name':'wyj', 'age':24})
'name' = 'wyj'
'age' = 24


当然,更复杂地,可以混合使用*arg, **arg, 默认值特性:
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn