代码改变世界

哗啦啦Python之路 - Day 4 - set,函数,深浅copy,装饰器

2016-05-22 11:24  人畜无害哗啦啦  阅读(186)  评论(0编辑  收藏  举报

1. dict类下面有哪些功能

  1 class dict(object):
  2     """
  3     dict() -> new empty dictionary
  4     dict(mapping) -> new dictionary initialized from a mapping object's
  5         (key, value) pairs
  6     dict(iterable) -> new dictionary initialized as if via:
  7         d = {}
  8         for k, v in iterable:
  9             d[k] = v
 10     dict(**kwargs) -> new dictionary initialized with the name=value pairs
 11         in the keyword argument list.  For example:  dict(one=1, two=2)
 12     """
 13 
 14     def clear(self): # real signature unknown; restored from __doc__
 15         """ 清除内容 """
 16         """ D.clear() -> None.  Remove all items from D. """
 17         pass
 18 
 19     def copy(self): # real signature unknown; restored from __doc__
 20         """ 浅拷贝 """
 21         """ D.copy() -> a shallow copy of D """
 22         pass
 23 
 24     @staticmethod # known case
 25     def fromkeys(S, v=None): # real signature unknown; restored from __doc__
 26         """
 27         dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
 28         v defaults to None.
 29         """
 30         pass
 31 
 32     def get(self, k, d=None): # real signature unknown; restored from __doc__
 33         """ 根据key获取值,d是默认值 """
 34         """ D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None. """
 35         pass
 36 
 37     def has_key(self, k): # real signature unknown; restored from __doc__
 38         """ 是否有key """
 39         """ D.has_key(k) -> True if D has a key k, else False """
 40         return False
 41 
 42     def items(self): # real signature unknown; restored from __doc__
 43         """ 所有项的列表形式 """
 44         """ D.items() -> list of D's (key, value) pairs, as 2-tuples """
 45         return []
 46 
 47     def iteritems(self): # real signature unknown; restored from __doc__
 48         """ 项可迭代 """
 49         """ D.iteritems() -> an iterator over the (key, value) items of D """
 50         pass
 51 
 52     def iterkeys(self): # real signature unknown; restored from __doc__
 53         """ key可迭代 """
 54         """ D.iterkeys() -> an iterator over the keys of D """
 55         pass
 56 
 57     def itervalues(self): # real signature unknown; restored from __doc__
 58         """ value可迭代 """
 59         """ D.itervalues() -> an iterator over the values of D """
 60         pass
 61 
 62     def keys(self): # real signature unknown; restored from __doc__
 63         """ 所有的key列表 """
 64         """ D.keys() -> list of D's keys """
 65         return []
 66 
 67     def pop(self, k, d=None): # real signature unknown; restored from __doc__
 68         """ 获取并在字典中移除 """
 69         """
 70         D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 71         If key is not found, d is returned if given, otherwise KeyError is raised
 72         """
 73         pass
 74 
 75     def popitem(self): # real signature unknown; restored from __doc__
 76         """ 获取并在字典中移除 """
 77         """
 78         D.popitem() -> (k, v), remove and return some (key, value) pair as a
 79         2-tuple; but raise KeyError if D is empty.
 80         """
 81         pass
 82 
 83     def setdefault(self, k, d=None): # real signature unknown; restored from __doc__
 84         """ 如果key不存在,则创建,如果存在,则返回已存在的值且不修改 """
 85         """ D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D """
 86         pass
 87 
 88     def update(self, E=None, **F): # known special case of dict.update
 89         """ 更新
 90             {'name':'alex', 'age': 18000}
 91             [('name','sbsbsb'),]
 92         """
 93         """
 94         D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 95         If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
 96         If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
 97         In either case, this is followed by: for k in F: D[k] = F[k]
 98         """
 99         pass
100 
101     def values(self): # real signature unknown; restored from __doc__
102         """ 所有的值 """
103         """ D.values() -> list of D's values """
104         return []
105 
106     def viewitems(self): # real signature unknown; restored from __doc__
107         """ 所有项,只是将内容保存至view对象中 """
108         """ D.viewitems() -> a set-like object providing a view on D's items """
109         pass
110 
111     def viewkeys(self): # real signature unknown; restored from __doc__
112         """ D.viewkeys() -> a set-like object providing a view on D's keys """
113         pass
114 
115     def viewvalues(self): # real signature unknown; restored from __doc__
116         """ D.viewvalues() -> an object providing a view on D's values """
117         pass
118 
119     def __cmp__(self, y): # real signature unknown; restored from __doc__
120         """ x.__cmp__(y) <==> cmp(x,y) """
121         pass
122 
123     def __contains__(self, k): # real signature unknown; restored from __doc__
124         """ D.__contains__(k) -> True if D has a key k, else False """
125         return False
126 
127     def __delitem__(self, y): # real signature unknown; restored from __doc__
128         """ x.__delitem__(y) <==> del x[y] """
129         pass
130 
131     def __eq__(self, y): # real signature unknown; restored from __doc__
132         """ x.__eq__(y) <==> x==y """
133         pass
134 
135     def __getattribute__(self, name): # real signature unknown; restored from __doc__
136         """ x.__getattribute__('name') <==> x.name """
137         pass
138 
139     def __getitem__(self, y): # real signature unknown; restored from __doc__
140         """ x.__getitem__(y) <==> x[y] """
141         pass
142 
143     def __ge__(self, y): # real signature unknown; restored from __doc__
144         """ x.__ge__(y) <==> x>=y """
145         pass
146 
147     def __gt__(self, y): # real signature unknown; restored from __doc__
148         """ x.__gt__(y) <==> x>y """
149         pass
150 
151     def __init__(self, seq=None, **kwargs): # known special case of dict.__init__
152         """
153         dict() -> new empty dictionary
154         dict(mapping) -> new dictionary initialized from a mapping object's
155             (key, value) pairs
156         dict(iterable) -> new dictionary initialized as if via:
157             d = {}
158             for k, v in iterable:
159                 d[k] = v
160         dict(**kwargs) -> new dictionary initialized with the name=value pairs
161             in the keyword argument list.  For example:  dict(one=1, two=2)
162         # (copied from class doc)
163         """
164         pass
165 
166     def __iter__(self): # real signature unknown; restored from __doc__
167         """ x.__iter__() <==> iter(x) """
168         pass
169 
170     def __len__(self): # real signature unknown; restored from __doc__
171         """ x.__len__() <==> len(x) """
172         pass
173 
174     def __le__(self, y): # real signature unknown; restored from __doc__
175         """ x.__le__(y) <==> x<=y """
176         pass
177 
178     def __lt__(self, y): # real signature unknown; restored from __doc__
179         """ x.__lt__(y) <==> x<y """
180         pass
181 
182     @staticmethod # known case of __new__
183     def __new__(S, *more): # real signature unknown; restored from __doc__
184         """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
185         pass
186 
187     def __ne__(self, y): # real signature unknown; restored from __doc__
188         """ x.__ne__(y) <==> x!=y """
189         pass
190 
191     def __repr__(self): # real signature unknown; restored from __doc__
192         """ x.__repr__() <==> repr(x) """
193         pass
194 
195     def __setitem__(self, i, y): # real signature unknown; restored from __doc__
196         """ x.__setitem__(i, y) <==> x[i]=y """
197         pass
198 
199     def __sizeof__(self): # real signature unknown; restored from __doc__
200         """ D.__sizeof__() -> size of D in memory, in bytes """
201         pass
202 
203     __hash__ = None
204 
205 dict
View Code

 

2. set

- set是无序没有重复的序列

- 创建:

  • m = {1,2} #字典的区别是字典是{1:2, 3:2}
  • set() #里面有东西就转成set,没有就是空set
  • set([1,2,2,1]) #结果是 [1,2]

- 操作:

  • s.add(123) # 一个一个添加
  • s.update() # 更新,括号里添加可以迭代的东西,比如列表
    • ,比如“alex”进去就变成 了a.l.e.x
  • s.clear(123)
  • difference:

 S1 = {11,22,33}

 S2 = {11,22,44}

 S3 = s1.difference(S2) # S3 = {33} # 前者不同于后者的

 S4 = s1.symmetric_difference(S2) # s4 = {33,44} #两个中间所有不同的

  • update

S1.difference_update(S2) #把S2中不一样的放到S1里面

S1.symmetric_difference_update(S2) #一样的

  •  移除指定元素

discard, remove, pop # 区别在于,discard没有的话不报错,remove报错,Pop随机移除并赋值,且不能加参数在后面的括号里

  • intersection(取交集)
  • Isdisjoint(判断有没有交集)
  • Issubset() #是不是子序列
  • Issuperset() #是不是父序列
  • Union() #取并集
  1 class set(object):
  2     """
  3     set() -> new empty set object
  4     set(iterable) -> new set object
  5      
  6     Build an unordered collection of unique elements.
  7     """
  8     def add(self, *args, **kwargs): # real signature unknown
  9         """
 10         Add an element to a set,添加元素
 11          
 12         This has no effect if the element is already present.
 13         """
 14         pass
 15  
 16     def clear(self, *args, **kwargs): # real signature unknown
 17         """ Remove all elements from this set. 清除内容"""
 18         pass
 19  
 20     def copy(self, *args, **kwargs): # real signature unknown
 21         """ Return a shallow copy of a set. 浅拷贝  """
 22         pass
 23  
 24     def difference(self, *args, **kwargs): # real signature unknown
 25         """
 26         Return the difference of two or more sets as a new set. A中存在,B中不存在
 27          
 28         (i.e. all elements that are in this set but not the others.)
 29         """
 30         pass
 31  
 32     def difference_update(self, *args, **kwargs): # real signature unknown
 33         """ Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
 34         pass
 35  
 36     def discard(self, *args, **kwargs): # real signature unknown
 37         """
 38         Remove an element from a set if it is a member.
 39          
 40         If the element is not a member, do nothing. 移除指定元素,不存在不保错
 41         """
 42         pass
 43  
 44     def intersection(self, *args, **kwargs): # real signature unknown
 45         """
 46         Return the intersection of two sets as a new set. 交集
 47          
 48         (i.e. all elements that are in both sets.)
 49         """
 50         pass
 51  
 52     def intersection_update(self, *args, **kwargs): # real signature unknown
 53         """ Update a set with the intersection of itself and another.  取交集并更更新到A中 """
 54         pass
 55  
 56     def isdisjoint(self, *args, **kwargs): # real signature unknown
 57         """ Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
 58         pass
 59  
 60     def issubset(self, *args, **kwargs): # real signature unknown
 61         """ Report whether another set contains this set.  是否是子序列"""
 62         pass
 63  
 64     def issuperset(self, *args, **kwargs): # real signature unknown
 65         """ Report whether this set contains another set. 是否是父序列"""
 66         pass
 67  
 68     def pop(self, *args, **kwargs): # real signature unknown
 69         """
 70         Remove and return an arbitrary set element.
 71         Raises KeyError if the set is empty. 移除元素
 72         """
 73         pass
 74  
 75     def remove(self, *args, **kwargs): # real signature unknown
 76         """
 77         Remove an element from a set; it must be a member.
 78          
 79         If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
 80         """
 81         pass
 82  
 83     def symmetric_difference(self, *args, **kwargs): # real signature unknown
 84         """
 85         Return the symmetric difference of two sets as a new set.  对称差集
 86          
 87         (i.e. all elements that are in exactly one of the sets.)
 88         """
 89         pass
 90  
 91     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
 92         """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
 93         pass
 94  
 95     def union(self, *args, **kwargs): # real signature unknown
 96         """
 97         Return the union of sets as a new set.  并集
 98          
 99         (i.e. all elements that are in either set.)
100         """
101         pass
102  
103     def update(self, *args, **kwargs): # real signature unknown
104         """ Update a set with the union of itself and others. 更新 """
105         pass
View Code

 

- 求旧字典里哪些字段需要删除,哪些需要更新,哪些需要添加

 1 old_dict = {
 2     "#1":8,
 3     "#2":4,
 4     "#4":2,
 5 }
 6 
 7 new_dict = {
 8     "#1":4,
 9     "#2":4,
10     "#3":2,
11 }
12 
13 old_dict = set(old_dict.keys())
14 new_dict = set(new_dict.keys())
15 s3 = old_dict.difference(new_dict) #应该删除S3
16 s4 = new_dict.difference(old_dict) #应该增加S4
17 s5 = old_dict.intersection(new_dict) #应该更新的
View Code

 

3. 函数

- python内置函数

 

ASCII码

 

 

 

- function用法

 


#如果赋值就会变成None,因为重新赋值了
li = [11,22,33,44,]
def fl(arg):
arg.append(55)
#li = fl(li)
fl(li)
print(li)

#将字符转换成utf-8
bytes()

#false的值
[],{},None, 0, '',()




检测传的值能否被调用,可以print出来看
callable()

##########随机验证码##################
import random #随机数模块
i = random.randrange(1,5) #给定范围内数字 1=< i < 5,包前不包后
m = chr(random.randrange(65,91)) #65 - 90代表着字母
print(i,m)

#六个随机字母,任意位置都可以出现数字
import random
li = []
for i in range(6):
r = random.randrange(0,5) #每一次循环过来的时候随机一次
if r == 2 or r == 4 :
i = random.randrange(0,10) # 65 - 90 是大写字母,97 - 122是小写字母,\
# 包前不包后所以后面要多加一位
li.append(str(i))
else:
i = random.randrange(97, 123)
c = chr(i)
li.append(c)
#列表拼接用join,但是元素必须都是字符串
result = ''.join(li)
print(result)


######编译#############
正常使用文件的顺序:
1. 读取文件内容Open,str到内存
2. python,把字符串编译到特殊代码
3. 执行代码

compile() 字符串编译成Python代码
exec() 执行Python代码,但是没有返回值
s = "print(123)"
r = compile(s,'str','exec')
exec(s)
eval(s)

single() 编译成单行的Python程序
eval() 执行成表达式,exec更厉害,但是eval有返回值
s = '8*8'
ret = eval(s)
print(ret)


#####快速获取一个类能提供哪些功能#########
print(dir(list))
help(list)


####共97页,每页显示10条,需要多少页######
r = divmod(97,10)
print(r)
结果是(9,7)
print(r[0])
print(r[1])

或者n1,n2 = divmod(x,y)


######enumerate()##### 列举

#对象和类的区别:“alex”就是对象,str是类
s = 'alex'
r = isinstance(s, str) #判断某一个对象是谁的类



########删选################
filter():函数返回True,将元素添加到列表里
map():函数返回修改后的值,将返回值添加到列表里

不用filter删选大于22的数
def f1(args):
result= []
for item in args:
if item > 22:
result.append(item)
return result
li = [11,22,33,44,55]
ret = f1(li)
print(ret)

用filter
def f2(a):
if a >22:
return True
li = [11,22,33,44,55]
ret = filter(f2,li) #相当于把li里所有的参数执行了一次f2
print(list(ret))

也可以这么写
lst = [11,22,33,44,55]
y = [a for a in lst if a > 22]
print(y)

lambda表达式来filter
li = [11,22,33,44,55]
result = filter(lambda a:a>22,li)
print(list(result))

map - 对一批数据进行一个统一的操作
每个数加100

第一种写法
li = [11,22,33,44,55]
def f1(args):
result = []
for i in li:
m = i + 100
result.append(m)
return result
n = f1(li)
print(list(n))

第二种写法
def f2(a):
return a + 100
result = map(f2,li)
print(list(result))

第三种写法
li = [11,22,33,44,55]
result = map(lambda a:a+100, li)
print(list(result))
#########################################


####全局变量VS局部变量#########
NAME = 'alex' #全局变量

def show():
a = 123 #局部变量
print(globals()) #全局变量
print(locals()) #局部变量

show()
##############################

######issubclass() #查看某个类是不是另一个类的子类iter() #创建迭代器len() #查看长度s = "李杰"b = bytes(s,encoding = 'utf-8')print(len(s),len(b)) #在python 3 结果是2, python 2结果就是6,因为一个是字符,一个是字节###################li = [1,2,3]print(max(li))print(min(li))print(sum(li))############################迭代器next()iter()#############################数字变字母,字母变数字ord()chr()##############################pow() 求平方property() 特性range() 范围repr()reversed() 翻转li = [11,22,33,]li.reverse()reversed(li)r = round() 四舍五入slice() 切片 基本等于s = 'sssssss' print(s[0:2])sorted() 排序 等于 li.sort()vars() 当前模块里有哪些变量zip() 列表合并f1 = ['alex',11,22,33]f2 = ['is',11,22,33]f3 = ['sb',11,22,33]r = zip(f1,f2,f3)print(' '.join(list(r)[0]))################

 

 

5. 装饰器

 

- 九步入门

 

第一步:最简单的函数,准备附加额外功能

1
2
3
4
5
6
7
8
# -*- coding:gbk -*-
'''示例1: 最简单的函数,表示调用了两次'''
 
def myfunc():
    print("myfunc() called.")
 
myfunc()
myfunc()

 

第二步:使用装饰函数在函数执行前和执行后分别附加额外功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# -*- coding:gbk -*-
'''示例2: 替换函数(装饰)
装饰函数的参数是被装饰的函数对象,返回原函数对象
装饰的实质语句: myfunc = deco(myfunc)'''
 
def deco(func):
    print("before myfunc() called.")
    func()
    print("  after myfunc() called.")
    return func
 
def myfunc():
    print(" myfunc() called.")
 
myfunc = deco(myfunc)
 
myfunc()
myfunc()

第三步:使用语法糖@来装饰函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# -*- coding:gbk -*-
'''示例3: 使用语法糖@来装饰函数,相当于“myfunc = deco(myfunc)”
但发现新函数只在第一次被调用,且原函数多调用了一次'''
 
def deco(func):
    print("before myfunc() called.")
    func()
    print("  after myfunc() called.")
    return func
 
@deco
def myfunc():
    print(" myfunc() called.")
 
myfunc()
myfunc()

第四步:使用内嵌包装函数来确保每次新函数都被调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding:gbk -*-
'''示例4: 使用内嵌包装函数来确保每次新函数都被调用,
内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装函数对象'''
 
def deco(func):
    def _deco():
        print("before myfunc() called.")
        func()
        print("  after myfunc() called.")
        # 不需要返回func,实际上应返回原函数的返回值
    return _deco
 
@deco
def myfunc():
    print(" myfunc() called.")
    return 'ok'
 
myfunc()
myfunc()

第五步:对带参数的函数进行装饰

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding:gbk -*-
'''示例5: 对带参数的函数进行装饰,
内嵌包装函数的形参和返回值与原函数相同,装饰函数返回内嵌包装函数对象'''
 
def deco(func):
    def _deco(a, b):
        print("before myfunc() called.")
        ret = func(a, b)
        print("  after myfunc() called. result: %s" % ret)
        return ret
    return _deco
 
@deco
def myfunc(a, b):
    print(" myfunc(%s,%s) called." % (a, b))
    return a + b
 
myfunc(1, 2)
myfunc(3, 4)

第六步:对参数数量不确定的函数进行装饰

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# -*- coding:gbk -*-
'''示例6: 对参数数量不确定的函数进行装饰,
参数用(*args, **kwargs),自动适应变参和命名参数'''
 
def deco(func):
    def _deco(*args, **kwargs):
        print("before %s called." % func.__name__)
        ret = func(*args, **kwargs)
        print("  after %s called. result: %s" % (func.__name__, ret))
        return ret
    return _deco
 
@deco
def myfunc(a, b):
    print(" myfunc(%s,%s) called." % (a, b))
    return a+b
 
@deco
def myfunc2(a, b, c):
    print(" myfunc2(%s,%s,%s) called." % (a, b, c))
    return a+b+c
 
myfunc(1, 2)
myfunc(3, 4)
myfunc2(1, 2, 3)
myfunc2(3, 4, 5)

第七步:让装饰器带参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# -*- coding:gbk -*-
'''示例7: 在示例4的基础上,让装饰器带参数,
和上一示例相比在外层多了一层包装。
装饰函数名实际上应更有意义些'''
 
def deco(arg):
    def _deco(func):
        def __deco():
            print("before %s called [%s]." % (func.__name__, arg))
            func()
            print("  after %s called [%s]." % (func.__name__, arg))
        return __deco
    return _deco
 
@deco("mymodule")
def myfunc():
    print(" myfunc() called.")
 
@deco("module2")
def myfunc2():
    print(" myfunc2() called.")
 
myfunc()
myfunc2()

第八步:让装饰器带 类 参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# -*- coding:gbk -*-
'''示例8: 装饰器带类参数'''
 
class locker:
    def __init__(self):
        print("locker.__init__() should be not called.")
         
    @staticmethod
    def acquire():
        print("locker.acquire() called.(这是静态方法)")
         
    @staticmethod
    def release():
        print("  locker.release() called.(不需要对象实例)")
 
def deco(cls):
    '''cls 必须实现acquire和release静态方法'''
    def _deco(func):
        def __deco():
            print("before %s called [%s]." % (func.__name__, cls))
            cls.acquire()
            try:
                return func()
            finally:
                cls.release()
        return __deco
    return _deco
 
@deco(locker)
def myfunc():
    print(" myfunc() called.")
 
myfunc()
myfunc()

第九步:装饰器带类参数,并分拆公共类到其他py文件中,同时演示了对一个函数应用多个装饰器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# -*- coding:gbk -*-
'''mylocker.py: 公共类 for 示例9.py'''
 
class mylocker:
    def __init__(self):
        print("mylocker.__init__() called.")
         
    @staticmethod
    def acquire():
        print("mylocker.acquire() called.")
         
    @staticmethod
    def unlock():
        print("  mylocker.unlock() called.")
 
class lockerex(mylocker):
    @staticmethod
    def acquire():
        print("lockerex.acquire() called.")
         
    @staticmethod
    def unlock():
        print("  lockerex.unlock() called.")
 
def lockhelper(cls):
    '''cls 必须实现acquire和release静态方法'''
    def _deco(func):
        def __deco(*args, **kwargs):
            print("before %s called." % func.__name__)
            cls.acquire()
            try:
                return func(*args, **kwargs)
            finally:
                cls.unlock()
        return __deco
    return _deco
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# -*- coding:gbk -*-
'''示例9: 装饰器带类参数,并分拆公共类到其他py文件中
同时演示了对一个函数应用多个装饰器'''
 
from mylocker import *
 
class example:
    @lockhelper(mylocker)
    def myfunc(self):
        print(" myfunc() called.")
 
    @lockhelper(mylocker)
    @lockhelper(lockerex)
    def myfunc2(self, a, b):
        print(" myfunc2() called.")
        return a + b
 
if __name__=="__main__":
    a = example()
    a.myfunc()
    print(a.myfunc())
    print(a.myfunc2(1, 2))
    print(a.myfunc2(3, 4))