Source: http://www.liaoxuefeng.com/
♥ Function
- In python, name of a function could be assigned to a variable, for example:
>>> a = abs;
>>> a(-12)
12
- function definition:
def funtion_name(input_variable):
function body
return variables # usually *return* signifies the end of the function,
# without which function will return *None*.
# Define a null function
def nop()
pass # *pass* could be used as a placeholder, to ensure a smooth running
def
- import a self-defined function:
from name_of_function_definition_file (without .py) import function_name
- two functions:
1 isinstance: check type of parameter;
2 raise TypeError('...'): return TypeError with '...' as additional information. - multiple returned values are actually one tuple;
Parameters
- Default parameters
Note that defalut parameters must be unchangable objects.
# Set 'Westeros' and 'dead' as default parameters for 'loaction' and 'status' respectively
def game_of_thorn(name, gender, location = 'Westeros', status = 'dead'):
print('name: ', name)
print('gender: ', gender)
print('location: ', location)
print('status: ', status)
>>> game_of_thorn('Eddard Satrk', 'M')
name: Eddard Stark
gender: M
location: Westeros
status: dead
>>> game_of_thorn('Benjen Stark', 'M', 'the Wall')
name: Roose Bolton
gender: M
location: the North
status: dead
# You could ignore the order of input parameters as long as you assign
# the inputs directly to certain parameters
>>> game_of_thorn('Cersei Lannister', 'F', status = 'alive')
name: Cersei Lannister
gender: F
location: Westeros
status: alive
- Variable parameters
# An example
def calc(*numbers):
sum = 0
for n in numbers: # variable parameters are treated as a tuple
sum = sum + n * n
return sum
>>> calc(1, 2)
5
>>> nums = [1, 2, 3]
>>> calc(*nums) # list or tuple inputs could be sent in as variables parameters as well
14
- Keyword parameter
Variable parameters are treated as a dict inside the function.
def person(name, age, **kw): # kw as keyword parameter
print('name:', name, 'age:', age, 'other:', kw)
>>> person('Michael', 30)
name: Michael age: 30 other: {}
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}
>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)
name: Jack age: 24 other: {'city': 'Beijing', 'job': 'Engineer'}
- Named keyword parameter
def person(name, age, *, city, job): # Only those using 'city' and 'job' as
# keys will be accepted as keyword parameters
print(name, age, city, job)
>>> person('Jack', 24, city='Beijing', job='Engineer')
Jack 24 Beijing Engineer
# if there is alrealy a variable parameters in the function, then '*,'
# is not needed for named keyword parameters
def person(name, age, *args, city, job):
print(name, age, args, city, job)
Note
1 for named keyword parameters, parameter name is always needed when using the function;
2 named keyword parameter could be assigned a default value;
3 all the parameters could be used in one time, while the input order should be: regular parameter, default parameter, variable parameter (*argus), named keyword parameter and keyword parameter(**kw).
# Any fuction could be called using func(*args, **kw)
def f1(a, b, c=0, *args, **kw):
print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)
def f2(a, b, c=0, *, d, **kw):
print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw)
>>> args = (1, 2, 3, 4)
>>> kw = {'d': 99, 'x': '#'}
>>> f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}
>>> args = (1, 2, 3)
>>> kw = {'d': 88, 'x': '#'}
>>> f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}
Recursive function
Recursive function is the one call itself. But a stack flow may appear with multiple recursion. One way to avoid the situation is : tail recursion.
A recursive function is tail recursive if the final result of the recursive call is the final result of the function itself (https://wiki.haskell.org/Tail_recursion). Tail recursion occupies constant RAM, thus could effectively avoid stack overflow during function calling.