1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 # Author:Source
4 import time,functools
5 #装饰器。本质上是函数,作用是为其它函数添加附加功能。
6 #原则:1、不能修改被装饰的函数的源代码 2、不能修改被装饰的函数的调用方式。
7 #为什么说本质上是函数呢?
8 def test():
#关键字是def
9 '别害怕,仅仅只是一个测试函数而已'
10 print(
"Don't worry.Just test.")
11 func = test
#func变量表示的是一个函数对象的实例
12 print(func)
#不带括号表示一个函数
13 print(func())
#带括号时候直接调用函数
14 def statistics_time(fuc):
15 '统计程序运算时间的函数'
16 time_begin =
time.time()
17 fuc()
18 time_finish =
time.time()
19 print(
"The function spend %s to run."%(time_finish-
time_begin))
20 statistics_time(test)
#它违反了装饰器的第二个原则
21 def statistics_time_2(fuc):
22 print(fuc)
23 return test
24 test = statistics_time_2(
'ojbk')
25 test()
#其中的print(fuc)作为了增加的功能
26 #高阶函数
27 #其一,在不修改函数的调用方式的情况下,返回值中包含函数名。其二,在不修改装饰函数的源代码的情况下,把一个函数名当作实参传给另一个函数
28 #满足其中一个就是高阶函数
29 def timer():
#函数嵌套
30 def deco():
31 pass
32 #高阶函数 + 函数嵌套 =》装饰器
33 def function_run_time(func):
34 '统计程序运行时间的高阶函数'
35 def internal():
36 time_begin =
time.time()
37 func()
38 time_finish =
time.time()
39 print(
"The function spend %s to run."%(time_finish-
time_begin))
40 return internal
41 @function_run_time
#类似与 test_1 = funtion_run_time(test_1)
42 def test_1():
43 '只是一个测试小程序而已'
44 time.sleep(1
)
45 print(
"Just test again.")
46 #test_1()
47 #匿名函数lambda
48 x_1 =
lambda x:x+7
49 print(x_1(7
))
50 (
lambda n:
print(n))(5
)
51 x_2 =
lambda n:
print(n)
52 x_2(5
)
53 #三元运算
54 x_3 =
lambda x:1
if x<5
else 2
55 print(x_3(1),x_3(5
))
56 #filter()按照一定的规则过滤+三元运算
57 res = filter(
lambda n:n>5,range(10
))
58 for i
in res:
59 print(i)
60 #map(),对传入的值按规律处理并覆盖原有数据。
61 x_4 = map(
lambda x:x*2,range(10
))
62 for i
in x_4:
63 print(i)
64 x_5 = [i*2
for i
in range(10)]
#列表生成式
65 print(x_5)
66 x_6= [
lambda i:i*2
for i
in range(10)]
#不晓得为什么读出来的是地址
67 #reduce,需要先调用fuctools。函数将一个数据集合中的所有数据进行下列操作:用传给reduce中的函数function(有两个参数)先对集合
68 #中的第1、2个元素进行操作,得到的结果再与第三个数据用function函数运算,最后得到一个结果。
69 def multiplication(x,y):
70 return x*
y
71 print(functools.reduce(multiplication,[1,2,3,4,5
]))
72 print(functools.reduce(
lambda x,y:x*y,[1,2,3,4,5
]))
73 print(functools.reduce(
lambda x,y:x+y,[1,2,3,4,5
]))
74 #生成器,都是迭代器对象只有在调用的时候才会生成相应的数据
75 #for example
76 builder = (i*2
for i
in range(3
))
77 # print(builder)#显示的是所在内存地址
78 # print(builder.__next__())
79 # print(builder.__next__())
80 # print(builder.__next__())#只记住当前位置,超出会报错
81 # print(next(builder))
82 # print(next(builder))
83 # print(next(builder))
84 # for i in builder:#要用这种方式才可以调用
85 # print(i)
86 #斐波那契函数,第三个数等于前两个数的和。
87 '''def Fibonacci(time):
88 x,y =0,1,
89 while time>0:
90 #print(y)
91 yield y#yield 的作用就是把一个函数变成一个 generator
92 x,y = y,x+y#带有 yield 的函数不再是一个普通函数,Python解释器会将其视为一个 generator
93 time -=1#执行到 yield b 时,fab 函数就返回一个迭代值,下次迭代时,代码从 yield b 的下一条语句继续执行,
94 # 而函数的本地变量看起来和上次中断执行前是完全一样的,于是函数继续执行,直到再次遇到 yield
95 return '-----done-----'
96 g = Fibonacci(10)
97 while True:
98 try:#正常执行程序执行try下的程序,执行出错时执行except里的
99 x = next(g)
100 print("g:",x)
101 except StopIteration as e:
102 print("Generator return value:",e.value)
103 break'''
104 '''def producer(name):
105 c1 = consumer("A")
106 c2 = consumer("B")
107 c1.__next__()
108 c2.__next__()
109 print("开始准备做包子了!")
110 for i in range(10):
111 time.sleep(0)
112 print("做了两个包子。")
113 c1.send(i)
114 c2.send(i)
115 def consumer(name):
116 print("准备吃包子了.")
117 while True:
118 baozi = yield
119 print("包子[%s]来了,被[%s]吃了!"%(baozi,name))
120 producer('Souce')'''
121 #包子程序开始从producer运行,运行到__next__()时候,唤醒yield执行含有yield的conseumer。运行到yield的时候,保存当前状态,返回
122 #继续运行producer,运行到producer的send后唤醒yield并传值给yield然后继续执行consumer。再次consumer的yield则保存状态返回到producer
123 #send继续运行
124 #迭代器,可以直接作用于for循环的数据类型。
125 #可迭代对象(iterable)for example:
126 from collections
import Iterable
127 print(isinstance([],Iterable))
#列表
128 print(isinstance([i*2
for i
in range(10)],Iterable))
#列表生成式
129 print(isinstance(builder,Iterable))
#生成器
130 print(isinstance((),Iterable))
#元组
131 print(isinstance(set([1,1,2,3]),Iterable))
#集合
132 print(isinstance({},Iterable))
#列表
133 print(isinstance(
'',Iterable))
#字符串
134 #可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
135 #for example:
136 from collections
import Iterator
137 print(isinstance(builder,Iterator))
#生成器
138 print(isinstance([],Iterator))
139 print(isinstance(iter({}),Iterator))
#iter()可以把list、dict、str等Iterable变成Iterator
140 print(isinstance(
'',Iterator))
141 #为什么list、dict、str等数据类型不是Iterator
142 '''这是因为Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据
143 时抛出StopIteration错误,可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实
144 现按需计算下一个数据,所以Iterator的计算是惰性的,只有在需要返回时它才会计算。
145 Iterator甚至可以表示一个无限大的数据流,例如全体自然数,而使用list是永远不可能存储全体自然数的。
146 '''
147 #for循环的本质上是通过不断调用next()函数实现的,例如:
148 #先获得Iterator对象
149 it_tor = iter([1,2,3,4,5
])
150 while True:
151 try:
152 #获得下一个值
153 x =
next(it_tor)
154 print(x)
155 except StopIteration:
156 break
157 #装饰器终极版,网站页面的浏览权限限制,也就是登录验证。
158 '''user,pawd='source','123456'
159 def verification(way):
160 def select(func):
161 def verify(*args,**kwargs):
162 username = input('username:'.strip())
163 password = input('password:'.strip())
164 if way=='local':
165 if username == user and password == pawd:
166 print('\033[32;1mwelecome your enter!\033[0m'.capitalize())
167 res = func(*args,**kwargs)
168 print('what?'.center(50,'*'))
169 return res
170 else:
171 print('\033[31;1minvalid username or password.\033[0m'.capitalize())
172 elif way=='ldap':
173 print("\033[33;1mI haven't learned.\033[0m")
174 return verify
175 return select
176 def first_door():
177 print('welcome to the first door.'.capitalize())
178 @verification(way='local') #send_door = verify
179 def second_door():
180 print('welcome to the second door.'.capitalize())
181 return 'This Ok'
182 @verification(way='ldap')
183 def third_door():
184 print('welcome to the third door.'.capitalize())
185 first_door()
186 print(second_door())
187 third_door()'''
188 #abs(),返回数字的绝对值
189 print(abs(-8
))
190 #all(),如果迭代器中所有元素都为真则返回真。记住一点非零为真。用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,
191 # 如果是返回 True,否则返回 False。
192 #元素除了是 0、空、FALSE 外都算 TRUE。
193 print(all((-8,2,3
)))
194 iterable_list = [i*2
for i
in range(10
)]
195 print(all(iterable_list))
196 #all()实质上是:
197 def all_function(iterable):
198 for element
in iterable:
199 if not element:
200 return False
201 return True
202 print(all_function([-2,6
,0]))
203 #any(),可迭代数据里任意一个数据为真则返回真,空列表返回假。
204 print(any([0]))
205 print(any([0,1
]))
206 #ascii(),把一个内存对象变为可打印字符串的形式
207 print(
"just test.")
208 print(ascii(
"just test."))
209 #bin(),将十进制转二进制
210 for i
in range(15
):
211 print(bin(i))
212 #bytearray(),能对数据进行修改。注意:字符串不能修改,二进制字节格式不能修改。bytearray() 方法返回一个新字节数组。这个数组
213 # 里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。
214 #class bytearray([source[, encoding[, errors]]])
215 print(bytearray([]))
216 a = bytearray([3,2,1])
#如果 source 为整数,则返回一个长度为 source 的初始化数组
217 print(a)
218 a.append(4
)
219 a[0] = 5
#修改字符
220 print(a)
221 bytearray_test =
'just test.'
222 b = bytearray(bytearray_test,
'utf-8')
#如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列
223 print(b[0],b[1],b[2])
#打印出来的是ASCII码
224 b[0] = 97
#能修改字符
225 print(b)
226 print(bytearray(iterable_list))
#如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数
227 iterable_list[1]=4
#修改
228 print(bytearray(iterable_list))
229 #callable(),可不可以调用。注意:后面可以加括号的就是可以调用的。
230 print(callable(input))
231 print(callable(type))
232 #chr(),查看数字对应的ascall。
233 print(chr(97
))
234 #ord(),查看ascall对应的数字。
235 print(ord(
'd'))
236 #classmethod()修饰符对应的函数不需要实例。
237 # 化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,
238 # 类的方法,实例化对象等。
239 class A(object):
240 bar = 1
241 def func1(self):
242 print(
"foo")
243 @classmethod
244 def func2(cls):
245 print(
"func2")
246 print(cls.bar)
247 cls().func1()
248 A.func2()
249 #compile,底层的用于将代码编译的过程.将一个字符串编译为字节代码。
250 str =
"for i in range(10):print(i)"
251 c = compile(str,
'',mode =
'exec')
252 exec(c)
253 #delattr()函数用于删除属性。delattr(x, 'foobar') 相等于 del x.foobar。
254 class coordinate:
255 x = 10
256 y = 8
257 z = 6
258 point =
coordinate()
259 print(
"x = ",point.x)
260 print(
"y = ",point.y)
261 print(
"z = ",point.z)
262 delattr(coordinate,
'x')
263 print(
"del x ")
264 print(
"y = ",point.y)
265 print(
"z = ",point.z)
266 #dict(),用于创建一个字典。
267 dic = dict()
#创建一个空字典
268 print(dic)
269 dict1 = dict(a = 1 ,b =
'b',c =
'good')
#传入关键字
270 print(dict1)
271 dict2 = dict(zip([
'one',
'two',
'three'],[1,2,3]))
#映射函数的方式构造字典
272 dict3 = dict([(
'nine',9),(
"eight",8),(
'seven',7)])
#可迭代对象方式构造字典
273 print(dict2,dict3)
274 #dir(),查看有什么方法可以用。dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、
275 # 方法列表。如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
276 print(dir())
#返回当前范围内的变量、方法和定义的类型列表。
277 print(dir(dict))
#带参数时,返回参数的属性、方法列表。
278 #divmod(a,b),相除返回商,余数。
279 print(divmod(6,3
))
280 #eval(),将字符串变成字典。注意(字符类型、加减乘除、难的不行).用来执行一个字符串表达式,并返回表达式的值。
281 x = 3
282 print(eval(
'3*x'))
283 print(eval(
'pow(2,3)'))
#2**3
284 print(eval(
'abs(-3/x)'))
285 #exec(),能处理男的eval()。例如循环
286 def Fibonacci_test_again(TIME):
287 x,y, = 0,1
288 while TIME>
0:
289 yield y
290 x,y = y,x+
y
291 TIME-=1
292 return 'Over maximum.'
293 g = Fibonacci_test_again(10
)
294 while True:
295 try:
296 x=
next(g)
297 print(
'g:',x)
298 except StopIteration as e:
299 print(
"Generator return value:",e.value)
300 break
301 #lambda,匿名函数。
302 (
lambda n:
print(
'n:',n))(5
)
303 cal =
lambda n:n
304 print(
'n:',cal(5
))
305 (
lambda n:
print(
'n大于2时n等于',1)
if n>2
else print(
'n小于等于2时n等于',5))(3)
#三元运算
306 #frozenset()返回一个冻结的集合,冻结后集合不能再添加或删除任何元素
307 set_test = frozenset([1,2,3,4,5,6,3,4,87,6
])
308 print(set_test)
309 #globals(),返回整个文件的变量的key-value,变量名key,内容是value.
310 print(globals())
311 #hash(),给输入的数据弄一个映射关系。用于获取取一个对象(字符串或者数值等)的哈希值
312 hash_test= hash(
'test')
313 print(hash_test,hash(1
))
314 #hex(),将10进制转化为16进制。
315 print(hex(10),hex(11),hex(12),hex(13),hex(14
))
316 #isinstance,函数来判断一个对象是否是一个已知的类型,类似 type()。
317 # isinstance() 与 type() 区别:type() 不会认为子类是一种父类类型,不考虑继承关系。isinstance() 会认为子类是一种父类类型,
318 # 考虑继承关系。如果要判断两个类型是否相同推荐使用 isinstance()。
319 number = 5
320 str_test =
'test'
321 number_type =
int
322 str_type =
str
323 print(isinstance(number,number_type))
324 print(type(str_test))
325 #print(isinstance(str_test,str_type))#不晓得为啥子不行的
326 #id(),返回内存地址。
327 print(id(number))
328 print(id(str_test))
329 #locals() 函数会以字典类型返回当前位置的全部局部变量。对于函数, 方法, lambda 函式, 类, 以及实现了 __call__ 方法的类实例,
330 # 它都返回 True。
331 def causal_test(*
args):
332 z =
args
333 print(locals())
334 causal_test(5
)
335 print(locals())
336 print(globals())
337 #max(),返回列表最大值。
338 list_test = [1,2,3,4,59,7,75,3,2
,]
339 print(max(list_test))
340 #oct(),函数将一个整数转换成8进制字符串。
341 print(oct(number))
342 print(oct(1),oct(2),oct(3),oct(4),oct(5),oct(6),oct(8),oct(9),oct(9),oct(10
))
343 #pow(),x的n次方。
344 print(pow(3,3
))
345 #repr(),与ascii类似。将对象转化为供解释器读取的形式
346 print(repr(
'test'))
347 print(repr({
'one':1,
"two":2
}))
348 #round()方法返回浮点数X的四舍五入值。
349 print(round(8.564
))
350 print(round(8.464
))
351 #slice(),函数实现切片对象,主要用在切片操作函数里的参数传递。
352 circulation = range(10
)
353 cut = slice(5
)
354 print(cut)
355 print(circulation)
356 print(circulation[cut])
357 #sorted(),可以给dictionary排序。
358 #sort与sorted区别:sort是应用在list上的方法,sorted可以对所有可迭代的对象进行排序操作。list 的 sort 方法返回的是对已经存在
359 #的列表进行操作,无返回值,而内建函数 sorted 方法返回的是一个新的 list,而不是在原来的基础上进行的操作。
360 list = [5,6,4,7,6,1,2,5,6,4
]
361 print(list)
362 list.sort()
363 print(list)
364 dictionary_test = {1:
'a',2:
'b',8:
'd',4:
'c',5:
'e'}
365 print(sorted(dictionary_test.items()))
366 print(sorted(dictionary_test.items(),key =
lambda y:y[1
]))
367 print(sorted(dictionary_test.items(),key =
lambda y:y[1],reverse =
True))
368 #vars(),返回一个对象的所有属性名
369 #zip(),拼接
370 A_number = [0,1,2,3,4,5
]
371 A_english = [
'zero',
'one',
'two',
'three',
'four',
'five']
372 for i
in zip(A_number,A_english):
373 print(i)
374 #_import___import__() 函数用于动态加载类和函数 。如果一个模块经常变化就可以使用 __import__() 来动态载入。
375 #json序列化,所谓的序列化也就是将内存对象变为字符串
376 import json
377 info =
{
378 "name":
'souce',
379 'age':23
380 }
381 f = open(
"test.test",
'w')
382 f.write(json.dumps(info))
383 f.close()
384 f = open(
"test.test",
'r')
385 data =
json.loads(f.read())
386 print(data[
'age'])
387 #有__init__的叫做包
388 # 1、json.dumps()和json.loads()是json格式处理函数(可以这么理解,json是字符串)
389 # (1)json.dumps()函数是将一个Python数据类型列表进行json格式的编码(可以这么理解,json.dumps()函数是将字典转化为字符串)
390 # (2)json.loads()函数是将json格式数据转换为字典(可以这么理解,json.loads()函数是将字符串转化为字典)
391 # 2、json.dump()和json.load()主要用来读写json文件函数
转载于:https://www.cnblogs.com/source12/p/9792296.html