定义一个什么都不做的函数
代码如下:
>>> def a():
... pass
...
>>> def printHello():
... print("hello")
...
>>> printHello()
hello
>>> callable(printHello)
True
有书上说,callable在Python3.0中已经不再使用,而使用hasattr(func, '__call__')代替;
代码如下:
>>> hasattr(printHello, '__call__')
True
>>> printHello.__doc__
>>> def printHello():
... 'just print hello'
... print('hello')
...
>>> printHello.__doc__
'just print hello'
代码如下:
>>> help(printHello)
函数的注释信息包含其中;
虽然printHello函数没有使用return,可以用一个变量接收返回值:
代码如下:
>>> result = printHello()
hello
>>> result
>>> print(result)
None
代码如下:
>>> def printStr(str):
... print(str)
…
>>> printStr("hello")
hello
代码如下:
>>> 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]
代码如下:
>>> a = [1,2]
>>> try_change_list(a[:])
>>> a
[1, 2]
代码如下:
>>> def sum(a=0, b=0):
... return a + b;
...
>>> sum(2,2)
4
>>> sum(b = 3, a = 4)
7
代码如下:
>>> def sum(*args):
... s = 0;
... for i in args:
... s += i;
... return s
...
>>> sum(1,2,3,4)
10
代码如下:
>>> 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
代码如下:
>>> 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