- 抽象
- 函数调用 抽象和结构 创建函数
hasattr(func,__call__)
:判断函数是否可调用- 斐波那契数列
def fibs(num): result = [0, 1] for i in range(num -2): result.append(result[-2] + result[-1]) return result
记录函数
- 字符串文档
>>>square.__doc__
并非真正函数的函数
- 无返回值的函数返回None 参数
- 形参和实参
- 参数可以改变吗?
函数内参数重新绑定,不会影响函数外部的变量,因为参数存储在局部作用域
-
传入列表
change(name[:]) change(names)
- 查询联系人
def lookup(data, label, name): return data[label].get(name)
def store(data, full_name):
names = full_name.split()
if len(names) == 2: names.insert(1,'')
lables = 'first', 'middle', 'last'
for label, name in zip(labels, names)
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]
###关键字参数和默认值
###收集参数
- *params
```python
def print_param(title,*params):
print(title)
print(params)
- **keys
def print_params(title,*params, **keys): print(title) print(params) print(keys)
print_params("hello",2,3,4, foo1='23',foo2='34'):
- 实现多个名字存储
```python
def store(data, *full_names):
for full_name in full_names:
names = full_name.split()
if len(names) == 2: names.insert(1,'')
lables = 'first', 'middle', 'last'
for label, name in zip(labels, names)
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]
反转过程
params = {'name': 'Sir Robin', 'greeting': 'wellmet'}
hello(**params)
练习使用参数
def story(**kwds):
return 'Once upon a time, there was a ' \
'%(job)s called %(name)s.' % kwds
def power(x, y, *others):
if others:
print 'Received redundant parameters:', others
return pow(x, y)
def interval(start, stop=None, step=1):
'Imitates range() for step > 0'
if stop is None: # If the stop is not supplied...
start, stop = 0, start # shuffle the parameters
result = []
i = start # We start counting at the start index
while i < stop: # Until the index reaches the stop index...
result.append(i) # ...append the index to out result...
i += step # ...increment the index with the step (> 0)
return result
作用域
- 命名空间:作用域,不可见字典
- Shadowing
globals().['parameter']
vars
locals
nonlocal
- 最小可能性问题
- 递归实例
阶乘和幂
另外一个经典:二元查找
def search(sequence, number, lower, upper=None):
if upper is None: upper = len(sequence)-1
if lower == upper:
assert number == sequence[upper]
return upper
else:
middle = (lower + upper) // 2
if number > sequence[middle]:
return search(sequence, number, middle+1, upper)
else:
return search(sequence, number, lower, middle)
本章新函数
- map(func, seq[, seq,...])
- filter(func,seq)
- reduce(func, seq[, initial])
- sum(seq)
- apply(func[, args[, kwargs]])