Python第一个基本教程6章 抽象的
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
#6.1 懒惰即美德 >>> fibs = [0,1]
>>> for i in range(8):
fibs.append(fibs[-2]+fibs[-1]) >>> fibs
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] # 你甚至能够将用户输入的数字作为动态范围的长度使用, 从而改变for语句块循环的次数
fibs=[0,1]
num = input('How many Fibonacci numbers do you want? ')
for i in range(num-2):
fibs.append(fibs[-2] + fibs[-1])
print fibs def fibs(num):
result = [0,1]
for i in range(num-2):
result.append(result[-2] + result[-1])
return result print fibs(10)
print fibs(15)
#[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
#[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] #6.2 抽象和结构
#page = download_page()
#freqs = compute_frequencies(page)
#for word,freq in freqs:
# print word,freq #6.3 创建函数
>>> import math
>>> x=1
>>> y=math.sqrt
>>> callable(x)
False
>>> callable(y)
True
>>> del hello(name): SyntaxError: invalid syntax
>>> def hello(name):
return 'Hello, ' + name + '!' >>> print hello('world')
Hello, world!
>>> print hello('Jonathan')
Hello, Jonathan!
>>> def fibs(num):
result = [0,1]
for i in range(num-2):
result.append(result[-2] + result[-1])
return result >>> fibs(10)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
>>> fibs(15)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377] #6.3.1 给函数写文档
>>> def square(x):
... 'Calculates the square of the number x.'
... return x*x
...
>>> square.__doc__
'Calculates the square of the number x.'
>>> help(square)
Help on function square in module __main__: square(x)
Calculates the square of the number x. #6.3.1 Python的有些函数并不返回不论什么东西(其实返回None)
>>> def test():
... print 'This is printed'
... return
... print 'This is not'
...
>>>
>>> x=test()
This is printed
>>> x
>>> print x
None #6.4.1 值从哪里来
#6.4.2 我能改变參数吗
#參数仅仅是变量而已. 在函数内为參数赋值不会改变外部不论什么变量的值
#參数存储在局部作用域(local scope)内
#字符串(以及数字和元组)是不可变的, 即无法被改动(也就是说仅仅能用心的值覆盖).
#但考虑一下假设将可变的数据结构如列表用作參数时会发生什么
>>> def try_to_change(n):
... n = 'Mr. Gumby'
...
>>> name = 'Mrs. Entity'
>>> try_to_change(name)
>>> name
'Mrs. Entity'
>>>
>>> name='Mrs. Entity'
>>> n = name #这句的作用基本上等于传參数
>>> n = 'Mr. Gumby' # 在函数内部完毕的
>>> name
'Mrs. Entity'
>>> def change(n):
... n[0] = 'Mr. Gumby'
...
>>> names = ['Mrs. Entity', 'Mrs. Thing']
>>> change(names)
>>> names
['Mr. Gumby', 'Mrs. Thing']
>>>
>>> names = 'Mrs. Entity', 'Mrs. Thing']
File "<stdin>", line 1
names = 'Mrs. Entity', 'Mrs. Thing']
^
SyntaxError: invalid syntax
>>> names = ['Mrs. Entity', 'Mrs. Thing']
>>> n = names # 再来一次, 模拟传參行为
>>> n[0] = 'Mr. Gumby' # 改变列表内容
>>> names
['Mr. Gumby', 'Mrs. Thing']
>>>
>>> names = ['Mrs. Entity','Mrs. Thing']
>>> n = names[:]
>>> n is names
False
>>> n is not names
True
>>> n == names
True
>>> n === names
File "<stdin>", line 1
n === names
^
SyntaxError: invalid syntax
>>> n[0]='Mr. Gumby'
>>> n
['Mr. Gumby', 'Mrs. Thing']
>>> names
['Mrs. Entity', 'Mrs. Thing']
>>> change(names[:])
>>> names
['Mrs. Entity', 'Mrs. Thing'] # 为什么我想要改动參数
>>> storage={}
>>> storage['first']={}
>>> storage['middle']={}
>>> storage['last']={}
>>> me = 'Magnus Lie Hetland'
>>> storage['first']['Magnus']=[me]
>>> storage['middle']['Lie']=[me]
>>> storage['last']['Hetland']=[me]
>>> storage['middle']['Lie']
['Magnus Lie Hetland']
>>>
>>> my_sister='Anne Lie Hetland'
>>> storage['first'].setdefault('Anne', []).append(my_syster)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'my_syster' is not defined
>>> storage['first'].setdefault('Anne', []).append(my_sister)
>>> storage['middle'].setdefault('Lie', []).append(my_sister)
>>> storage['last'].setdefault('Hetland', []).append(my_sister)
>>> storage['first']['Anne']
['Anne Lie Hetland']
>>> storage['middle']['Lie']
['Magnus Lie Hetland', 'Anne Lie Hetland']
>>>
>>> def init(data):
... data['first']={}
... data['middle']={}
... data['last']={}
...
>>> storage = {}
>>> init(storage)
>>> storage
{'middle': {}, 'last': {}, 'first': {}}
>>>
>>> def lookup(data, label, name):
... return data[lable].get(name)
...
>>> lookup(storage, 'middle', 'Lie')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in lookup
NameError: global name 'lable' is not defined
>>> def lookup(data, label, name):
... return data[label].get(name)
...
>>> lookup(storage, 'middle', 'Lie')
>>> print lookup(storage, 'middle', 'Lie')
None
>>> def store(data, full_name):
... names = full_name.split()
... if len(names) == 2: names.insert(1, '')
... labels = 'first', 'middle', 'last'
... for label, name in zip(labels, names)
File "<stdin>", line 5
for label, name in zip(labels, names)
^
SyntaxError: invalid syntax
>>> def store(data, full_name):
... names = full_name.split()
... if len(names) == 2: names.insert(1, '')
... labels = '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]
...
>>> MyNames = {}
>>> init(MyNames)
>>> store(MyNames, 'Magnus Lie Hetland')
>>> lookup(MyNames, 'middle', 'Lie')
['Magnus Lie Hetland']
>>>
>>> store(MyNames, 'Robin Hood')
>>> store(MyNames, 'Robin Locksley')
>>> lookup(MyNames, 'first', 'Robin')
['Robin Hood', 'Robin Locksley']
>>> store(MyNames, 'Mr. Gumby')
>>> lookup(MyNames, 'middle, '')
File "<stdin>", line 1
lookup(MyNames, 'middle, '')
^
SyntaxError: EOL while scanning string literal
>>> lookup(MyNames, 'middle','')
['Robin Hood', 'Robin Locksley', 'Mr. Gumby']
>>> def inc(x): return x+1
... # 假设我的參数不可变呢
# 这个时候你应该从函数中返回全部你须要的值(假设值多于一个就以元组形式返回)
>>> foo = 10
>>> foo = inc(foo)
>>> foo
11
# 假设真的想改变參数, 那么能够使用一点小技巧, 即将值放置在列表中
>>> def inc(x): x[0] = x[0] + 1
...
>>> foo = [10]
>>> inc(foo)
>>> foo
[11] #6.4.3 位置參数, keyword參数 和 默认值
>>>
>>> def hello_1(greeting, name):
... print '%s, $s!' % (greeting, name)
...
>>> def hello_2(name, greeting):
... print '%s, %s!' % (name, greeting)
...
>>> hello_1('Hello','world')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in hello_1
TypeError: not all arguments converted during string formatting
>>> def hello_1(greeting, name):
... print '%s, %s!' % (greeting, name)
...
>>> hello_1('Hello','world')
Hello, world!
>>> hello_2('Hello','world')
Hello, world!
>>> hello_1(greeting='Hello', name='world')
Hello, world!
>>> hello_1(name='world',greeting='Hello')
Hello, world!
>>> hello_2(name='world',greeting='Hello')
world, Hello!
>>> # store('Mr. Brainsample', 10, 20, 13, 5)
...
>>> # store(patient='Mr. Brainsample', hour=10, minute=20, day=13, month=5)
...
>>> def hello_3(greeting='Hello', name='world'):
... print '%s, %s!' % (greeting, name)
...
>>> hello_3()
Hello, world!
>>> hello_3('Greetings')
Greetings, world!
>>> hello_3('Greetings', 'universe')
Greetings, universe!
>>> hello_3(name='Gumby')
Hello, Gumby!
>>>
>>> def hello_4(name, greeting='Hello', punctuation='!'):
... print '%s, %s%s' % (greeting, name, punctuation)
...
>>> hello_4('Mars)
File "<stdin>", line 1
hello_4('Mars)
^
SyntaxError: EOL while scanning string literal
>>> hello_4('Mars')
Hello, Mars!
>>> hello_4('Mars', 'Howdy')
Howdy, Mars!
>>> hello_4('Mars', 'Howdy', '...')
Howdy, Mars...
>>> hello_4('Mars','...')
..., Mars!
>>> hello_4('Mars', punctuation = '...')
Hello, Mars...
>>> hello_4('Mars', punctuation = '.')
Hello, Mars.
>>> hello_4('Mars', greeting='Top of the morning to ya')
Top of the morning to ya, Mars!
>>> hello_4()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: hello_4() takes at least 1 argument (0 given) #6.4.4 收集參数
>>> # store(data, name1, name2, name3)
...
>>> def print_params(*params):
... print params
...
>>> print_params('Testing')
('Testing',)
>>> print_params(1,2,3)
(1, 2, 3)
>>> def print_params_2(title, *params)
File "<stdin>", line 1
def print_params_2(title, *params)
^
SyntaxError: invalid syntax
>>> def print_params_2(title, *params):
... print title
... print params
...
>>> print_params('Params:', 1,2,3)
('Params:', 1, 2, 3)
>>> print_params_2('Params:', 1,2,3)
Params:
(1, 2, 3)
>>> print_params_2('Nothing')
Nothing
()
>>> print_params_2('Nothing:')
Nothing:
()
>>> print_params_2('Hmm...', something=42)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: print_params_2() got an unexpected keyword argument 'something'
>>> def print_params_3(**params):
... print params
...
>>> print_params_3(x=1, y=2, z=3)
{'y': 2, 'x': 1, 'z': 3}
>>> def print_params_4(x, y, z=3, *pospar, **keypar):
... print x,y,z
... print pospar
... print keypar
...
>>> print_params_4(1,2,3,5,6,7,foo=1,bar=2)
1 2 3
(5, 6, 7)
{'foo': 1, 'bar': 2}
>>> print_params_4(1,2)
1 2 3
()
{}
>>> def store(data, *full_names);
File "<stdin>", line 1
def store(data, *full_names);
^
SyntaxError: invalid syntax
>>> def store(data, *full_names):
... for full_name in full_names:
... names = full_name.split()
... if len(names) == 2: names.insert(1,'')
... labels = '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]
...
>>> d = {}
>>> init(d)
>>> store(d, 'Han Solo')
>>> store(d, 'Luke Skywalker', 'Anakin Skywalker')
>>> lookup(d, 'last', 'Skywalker')
['Luke Skywalker', 'Anakin Skywalker'] #6.4.5 反转过程
#怎样将參数收集为 元组 和 字典 已经讨论过了, 可是其实, 假设使用 * 和 **的话, 也能够运行相反的操作. 那么參数收集的逆过程是什么样的?
>>> def add(x,y): return x+y
...
>>> params = (1,2)
>>> add(*params)
3
>>> params = {'name':'Sir Robin', 'greeting':'Well met'}
>>> def hello_3(greeting='Hello', name='world'):
... print '%s, %s!' % (greeting, name)
...
>>> hello_3(**params)
Well met, Sir Robin!
>>> def with_stars(**kwds):
... print kwds['name'], 'is', kwds['age'], 'years old'
...
>>> def without_stars(kwds):
... print kwds['name'], 'is', kwds['age'], 'years old'
...
>>> args={'name':'Mr. Gumby', 'age':42}
>>> with_stars(**args)
Mr. Gumby is 42 years old
>>> without_stars(args)
Mr. Gumby is 42 years old
>>>
>>> def foo(x,y,z,m=0,n=0):
... print x,y,z,m,n
... def call_foo(*args, **kwds):
File "<stdin>", line 3
def call_foo(*args, **kwds):
^
SyntaxError: invalid syntax
>>> def call_foo(*args, **kwds):
... print 'Calling too!'
... foo(*args, **kwds)
... #6.4.6 练习使用參数
#coding=utf-8
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):
'Imatates range() for step > 0'
if stop is None: #假设没有为stop提供值
start,stop = 0,start #指定參数, 连锁赋值
result = []
i = start #计算start索引
while i < stop: #直到计算到stop的索引
result.append(i) #将索引加入到result内...
i += step #用step(>0)添加索引i...
return result print story(job='king', name='Gumby')
print story(name='Sir Robin', job='brave knight')
params = {'job':'language', 'name':'Python'}
print story(**params)
del params['job']
print story(job='stroke of genius', **params)
print power(2,3)
print power(3,2)
print power(y=3,x=2)
params = (5,) * 2
print power(*params)
print power(3, 3, 'Hello, world')
print interval(10)
print interval(1, 5)
print interval(3,12,4)
print power(*interval(3,7)) #Once upon a time, there was a king called Gumby.
#Once upon a time, there was a brave knight called Sir Robin.
#Once upon a time, there was a language called Python.
#Once upon a time, there was a stroke of genius called Python.
#8
#9
#8
#3125
#Received redundant parameters: ('Hello, world',)
#27
#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
#[1, 2, 3, 4]
#[3, 7, 11]
#Received redundant parameters: (5, 6)
#81 #6.5 作用域
#究竟什么是变量? 你能够把它们看做是值的名字. 当然, 变量和所相应的值所用的是个"不可见"的字典. 内建的vars()函数能够返回这个字典
>>> x=1
>>> scope=vars()
>>> scope['x']
1
>>> scope['x'] += 1
>>> x
2 >>> def foo(): x=42
...
>>> x=1
>>> foo()
>>> x
1
>>> def output(x): print x
...
>>> x=1
>>> y=2
>>> output(y)
2
>>> def combine(parameter): print parameter + external
...
>>> external = 'berry'
>>> combine('Shrub')
Shrubberry
>>> # 屏蔽(Shadowing)的问题
>>> def combine(parameter):
... print parameter + globals()['parameter']
...
>>> parameter='berry'
>>> combine('straw')
strawberry
>>>
>>> x=1
>>> def change_global():
... global x
... x += 1
...
>>> change_global()
>>> x
2 # 嵌套作用域
# Python的函数是能够嵌套的.
>>> def foo():
... def bar():
... print "Hello, world!"
... bar()
...
>>> def multiplier(factor):
... def multiplyByFactor(number):
... return number*factor
... return multiplyByFactor
...
>>> double = multiplier(2)
>>> double(5)
10
>>> triple = multiplier(3)
>>> triple(3)
9
>>> multiplier(5)(4)
20 #6.6 递归
# 实用的递归函数包含下面几部分:
# 1) 当函数直接返回值时有 基本实例 (最小可能性问题);
# 2) 递归实例, 包含一个或多个问题最小部分的递归调用. #6.6.1 两个经典: 阶乘 和 幂次运算
>>> def recursion():
... return recursion()
...
>>> def factorial(n):
... result = n
... for i in range(1,n):
... result *= i
... return result
...
>>> factorial(10)
3628800
>>> def factorial(n):
... if n==1:
... return 1
... else:
... return n * factorial(n-1)
...
>>> factorial(10)
3628800
>>> def power(x,n):
... result = 1
... for i in range(n):
... result *= x
... return result
...
>>> def power(x,n):
... if n==0:
... return 1
... else:
... return x * power(x, n-1)
...
>>> power(2,3)
8
>>> # 6.6.2 另外一个经典: 二元查找
# 提示: 标准库中的bisect模块能够很有效地实现二元查找
def search(sequence, number, lower=0, 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) seq = [4, 8, 34, 67, 95, 100, 123]
seq.sort()
print search(seq, 34)
#2
print search(seq, 100)
#5 # Python在应对这类"函数式编程"方面, 有一些实用的函数: map, filter 和 reduce 函数(Python3.1中这些都被移到functools模块中)
# map和filter函数能够使用 列表推导式 取代
>>> [str(i) for i in range(10)]
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> map(str, range(10))
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] >>> seq = ["foo", "x41", "?!", "***"] >>> def func(x):
... return x.isalnum()
...
>>> filter(func, seq)
['foo', 'x41']
>>> [x for x in seq if x.isalnum()]
['foo', 'x41'] >>> filter(lambda x: x.isalnum(), seq)
['foo', 'x41']
>>> numbers = [72,101,108,108,111,44,32,119,111,114,108,100,33] >>> reduce(lambda x, y: x+y, numbers)
1161 sum(numbers)
1161
>>> sum=0
>>> for i in numbers:
... sum += i
...
>>> sum
1161 #6.7 小结: 关于抽象的常识以及函数的特殊知识
# 抽象:抽象是隐藏多余细节的艺术. 定义处理细节的函数能够让程序更抽象
# 函数定义: 函数使用def语句定义.
# 參数: 位置參数 和 keyword參数. 參数在给定默认值时是可选的
# 作用域: 变量存储在作用域(也叫做 命名空间). 全局作用域 和 局部作用域. 作用域能够嵌套.
# 递归: 函数能够调用自身. 一切用递归实现的功能都能够用循环实现, 但有时递归函数更易读.
# 函数式编程: 包含lambda表达式, 以及map, filter 和 reduce函数 #6.7.1 新函数
#map(func, seq[, seq, ...]) 对序列中的每一个元素应用函数
#filter(func, seq) 返回其函数为真的元素的列表
#reduce(func, seq [, initial]) 等同于func(func(func(seq[0],seq[1]), seq[2[),...)
#sum(seq) 返回seq中全部元素的和
#apply(func[, args[, kwargs]]) 通话功能, 我们可以提供的功能
版权声明:本文博主原创文章,博客,未经同意不得转载。
Python第一个基本教程6章 抽象的的更多相关文章
- Python第一个基本教程4章 词典: 当指数不工作时也
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type "copyri ...
- 简学Python第一章__进入PY的世界
#cnblogs_post_body h2 { background: linear-gradient(to bottom, #18c0ff 0%,#0c7eff 100%); color: #fff ...
- python第一章:简介与安装--小白博客
Python简介 Python是一种计算机程序设计语言.是一种动态的.面向对象的脚本语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越来越多被用于独立的.大型项 ...
- Python+Django+SAE系列教程17-----authauth (认证与授权)系统1
通过session,我们能够在多次浏览器请求中保持数据,接下来的部分就是用session来处理用户登录了. 当然,不能仅凭用户的一面之词,我们就相信,所以我们须要认证. 当然了,Django 也提供了 ...
- Python之Numpy详细教程
NumPy - 简介 NumPy 是一个 Python 包. 它代表 “Numeric Python”. 它是一个由多维数组对象和用于处理数组的例程集合组成的库. Numeric,即 NumPy 的前 ...
- Objective-C 基础教程第九章,内存管理
目录 Object-C 基础教程第九章,内存管理 前言: 对象生命周期 引用计数 RetainCount1项目例子 对象所有权 访问方法中的保留和释放 自动释放 所有对象放入池中 自动释放池的销毁时间 ...
- 学习opencv中文版教程——第二章
学习opencv中文版教程——第二章 所有案例,跑起来~~~然而并没有都跑起来...我只把我能跑的都尽量跑了,毕竟看书还是很生硬,能运行能出结果,才比较好. 越着急,心越慌,越是着急,越要慢,越是陌生 ...
- python学习笔记4_类和更抽象
python学习笔记4_类和更抽象 一.对象 class 对象主要有三个特性,继承.封装.多态.python的核心. 1.多态.封装.继承 多态,就算不知道变量所引用的类型,还是可以操作对象,根据类型 ...
- 「Python」pandas入门教程
pandas适合于许多不同类型的数据,包括: 具有异构类型列的表格数据,例如SQL表格或Excel数据 有序和无序(不一定是固定频率)时间序列数据. 具有行列标签的任意矩阵数据(均匀类型或不同类型) ...
随机推荐
- 搭建ganglia集群而且监视hadoop CDH4.6
前言 近期在研究云监控的相关工具,感觉ganglia颇有亮点,能从一个集群总体的角度来展现数据. 但是安装过程稍过复杂,相关依赖稍多,故写此文章与大家分享下. 本文不解说相关原理,若想了解请參考其它资 ...
- OSGI学习总结
最近的一项研究了解了一下OSGI技术,感觉OSGI尽管有一定的学习难度.可是终于掌握和推广之后将是一项对系统开发比較实用的技术.在此和大家分享一下自己的感悟. 1.什么是OSGI OSGI直译为&qu ...
- UVa 442 Matrix Chain Multiplication(矩阵链,模拟栈)
意甲冠军 由于矩阵乘法计算链表达的数量,需要的计算 后的电流等于行的矩阵的矩阵的列数 他们乘足够的人才 非法输出error 输入是严格合法的 即使仅仅有两个相乘也会用括号括起来 并且括号中 ...
- windows phone (22) 隐藏元素
原文:windows phone (22) 隐藏元素 在wp中我们也会用到隐藏某个元素,已达到某种效果,刚刚从文章看到了,分享一下[作者:神舟龙] Visibility 此属性能非常方便的实现隐藏某个 ...
- mybatis与mysql插入时返回主键id的值
<insert id="insertCharge" parameterType="com.bb.bean.Rechargerecord"> < ...
- Effective C++:规定20: 宁pass-by-reference-to-const更换pass-by-value
(一) 假设传递参数当函数被调用pass-by-value,然后函数的参数是基于实际参数的副本最初值,调用,也得到该函数返回的结束值复印件. 请看下面的代码: class Person { publi ...
- C++ Primer 学习笔记_53_类和数据抽象 --友元、static员
分类 --友元.static成员 一.友元 友元机制同意一个类将对其.友元关系:一个样例 如果一个窗体管理类Window_Mgr可能须要訪问由其管理的Screen对象的内部数据.Screen应该同意其 ...
- 玩转html5(三)---智能表单(form),使排版更加方便
<!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/h ...
- 【原创】leetCodeOj --- Sort List 解题报告
今日leetcode链表题全制霸 原题地址: https://oj.leetcode.com/problems/sort-list/ 题目内容: Sort List Sort a linked lis ...
- 微信公众平台入门--PHP,实现自身的主动回复文本,图像,点击事件
微通道基本应答代码,然后单击事件函数,部署了sae要么bae,基本自由妥妥server 号了 <?php define("TOKEN", "mzh"); ...