1、类的变量是全部的对象所共有,所以一旦某个对象更改了该变量的值, 其余的所有对象引用该变量时,都改变了 2、对象的变量,各个对象自己保存,并更改 有两种类型的 域 ——类的变量和对象的变量,它们根据是类还是对象 拥有 这个变量而区分。 类的变量 由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象 对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。 对象的变量
由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是
共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相 关的。通过一个例子会使这个易于理解。 3、def make_repeater(n): return lambda s: s*n twice = make_repeater(2) print twice('word') print twice(5) 不懂 4、指定编码: # -*- coding: utf-8 -*- 5、list中,直接访问是访问该对象,如果不想该变原来的值,可以用切片 a = ['ss','ff'] ->切片 a[:] 6、range函数可以产生一定范围的数据 range(3) ---> 0,1,2 range(1,5) --->1,2,3,4 range(1,5,2) --->1,3 7、在交互模式下,计算的表达式的结果保存在 '_' 中 如: price = 10 tax = 5 price * tax _ ->50 8、切片的第一个缺损默认是0, 第二个缺损默认是到字符串的最后, 因此,两个都缺损就是全部 9、顺序存储类型(7种):str,unicode, list, tuple(元组),bytearray, buffer, xrange str -> 'string' or "string" unicode -> u'stirng' or u"string" list ->['a',1, 'b'] tuple ->('abc','def'),单个元组必须有括号 ,(d,) bytearray ->由函数bytearray()创建
buffer ->由函数buffer()创建 xrange ->由函数xrange()创建,不支持切片,连接,重复,使用 in, not in, min(), max() 操作 10、list replace some items: a[0:2] = [1, 12] remover some: a[0:2] = [] insert some: a[1:1] = ['ss','bb'] insert a copy of itself at the beginning a[:0] = a len(a) ->查看数据多少,只看第一级 a.append('some') ->添加元素 11、for ->else 或 while -> else 当for正常结束时,或while正常结束时,else执行 但当在for或者while中是因为break语句结束时,else不执行 12、函数名是一个对象的引用,可以赋值给其他的对象,但引用的任然是该函数 如: def fib(): print 'ss' fib -><function fib at 0xb728e1b4> f = fib f -><function fib at 0xb728e1b4> 两个名字的引用地址是相同的,但名称不同,指向同一个对象 13、在定义函数时,*args 和 **args, *args 接受元组,所以参数中没有关键字,如key = 'value',而是,'value' **args 接收字典,所以参数中是 key = 'value' 14、函数定义时,可以指定参数的key,然后在传参数时,可以用字典,或key传
如: def fun( a, b = 'ss', c = 'dd') dict = {'a':'al','b':'ba','c':'cd'} fun(dict) 或者 fun(a = 1, b = '33',c = 'rr') 15、使用list可以模拟栈,结合cllections.deque,可以模拟队列 16、功能性的编程工具 filter,map,reduce filter(function, sequence),函数返回true的被留下,返回到sequence中 如: >>> def f(x): return x % 2 != 0 and x % 3 != 0 >>> ...
>>> filter(f, range(2, 25)) >>> [5, 7, 11, 13, 17, 19, 23] map(function, sequence),返回一个对象,该对象是对传入sequence的元素操作 后返回的对象,返回的对想保存在sequence中,返回 注:可以传入多个参数,如果一个参数的元素不够,则传入None 如: >>> def cube(x): return x*x*x >>> ...
>>> map(cube, range(1, 11)) >>> [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] 如: >>> seq = range(8) >>> def add(x, y): return x+y
>>> map(add, seq, seq) >>> [0, 2, 4, 6, 8, 10, 12, 14] reduce(function, sequence),对sequence中的元素进行计算,计算完毕后最终 返回一个值 如: >>> def add(x,y): return x+y >>> reduce(add, range(1, 11)) >>> 55 17.遍历二维list 如:
matrix = [ range(1,5), range(5,9), range(9, 13) ] 18.元组 元组的值不能更改,但可更改其中包含的可变的list 如: a = ['a','b'] c = a,'c' c ->(['a','b'],'c') c[0][0] = d c ->(['d','b'],'c') 19.Sets eng: Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference 译:Python 也包括数据类型sets(集合), 一个集合是无序的,没有重复元素的, 基本使用方法是:成员检测,和消除重复元素,集合对象也支持数学操作, 如:并集、交集、差集、和对称差 其中对称差:(A-B) U (B-A),元素不同时在两个集合中 1.创建一个集合用大括号{}或者用set()函数,创建空集用set(),而不是{} 2.测试成员是否在集合中 a = ['123','22'] b = set(a) if '22' in b: ->True 3.集合操作: A = set('abcdef') B = set('defigh') 交集:C = A & B 并集:C = A | B 差集:C = A - B 对称差:C = A ^ B 4.过滤操作 >>> a = {x for x in 'abracadabra' if x not in 'abc'} >>> a >>> set(['r', 'd']) 20.字典 eng:
Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend(). 译:另一个有用的python内置的数据类型是字典(see Mapping Types -dict) 有时候可以在其他语言中找到把字典当作'关系记忆'或'关联数组',不像 顺序存储,字典由一系列数字索引,字典由键来索引,键可以是任何不可 变的类型;字符串和数字总是那来做键,元组可以做键,仅当元组只含,字 符串、数字、或元组时,如果元组直接的或间接的含可变元素,将不可以做 键,不能那list来做键,因为list可以被修改,使用索引赋值,切片赋值, 或像方法append()和extend() 1.使用keys()获取字典的所有key 如:
tel = {"sss":12321,"sdf",1231} tel.keys() ->['sss','sdf'] 2、是用in操作符判断值是否存在 if 'sss' in tel: ->True 3.使用dict()构造函数可以从顺序存储的键值对中够着字典 如: >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) >>> {'sape': 4139, 'jack': 4098, 'guido': 4127} 4.循环遍历构造字典 如:
>>> {x: x**2 for x in (2, 4, 6)} {2: 4, 4: 16, 6: 36} 5.可以使用等号'='来创建简单的字典 >>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'jack': 4098, 'guido': 4127} 21.循环技巧 1.使用enumerate()函数可以同时取得索引和值 如: for i, v in enumerate(['tic','tac','toe']) print i,v 0 tic 1 tac 2 toe 2.遍历两个或更多的序列,可以用zip()函数来同时访问相应的元素 如: >>> questions = ['name', 'quest', 'favorite color'] >>> answers = ['lancelot', 'the holy grail', 'blue'] >>> for q, a in zip(questions, answers): ... print 'What is your {0}? It is {1}.'.format(q, a) or print 'What is your %s? It is %s. ' % (q, a) ... What is your name? It is lancelot. What is your quest? It is the holy grail. What is your favorite color? It is blue. 3.逆序遍历,可用函数xrange() for in reversed(xrange(1,5,2)): print i 4 2 4.使用sorted()函数可以对list排序 basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] >>> for f in sorted(set(basket)): ... print f apple banana orange pear 5.当遍历字典时,可以使用iteriems()函数,可同时获得key和value 如: >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} >>> for k, v in knights.iteritems(): ... print k, v gallahad the pure robin the brave 6.推荐在遍历时,使用切片复制一个备份操作 如: >>>words = ['cat', 'window', 'defenestrate'] >>>for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) >>>words ['defenestrate', 'cat', 'window', 'defenestrate']