# 不能修改被装饰的函数的功能;不能修改被装饰的函数的调用方式
'''
def logger():
print("logging")
def test1():
pass
logger()
def test2():
pass
logger()
test1()
test2()
'''
import time
def timmer(func):
def warpper(*args, **kwargs):
start_time=time.time()
func()
stop_time=time.time()
print('the func run time is %s' %(stop_time-start_time))
return warpper
@timmer
def test1():
time.sleep(3)
print('in the test1')
test1()
# 实现装饰器知识储备:1.函数即“变量”;2.高阶函数;3.嵌套函数
# 高阶函数+嵌套函数=装饰器
def foo():
print('in the foo')
bar()
foo()
def bar():
print('in the bar')
def foo():
print('in the foo')
bar()
foo()
# 匿名函数
calc = lambda x:x*3
print(calc(3))
def bar():
print('in the bar')
def test1(func):
print(func)
func()
test1(bar)
def bar():
time.sleep(3)
print('in the bar')
def test1(func):
start_time=time.time()
func()
stop_time=time.time()
print('the func run time is %s' %(stop_time-start_time))
test1(bar)
def test2(func):
print(func)
return func
bar = test2(bar)
bar()
# 嵌套函数
def foo():
print('in the foo')
def bar():
print('in the bar')
bar()
foo()
# 局部作用域和全局作用域的访问顺序
x=0
def grandpa():
# x=1
def dad():
x=2
def son():
x=3
print(x)
son()
dad()
grandpa()
##############################
import time
def timer(func): # timer(test1) func=test1
def deco(*args,**kwargs):
start_time=time.time()
func(*args,**kwargs) # run test1()
stop_time=time.time()
print('the func run time is %s' %(stop_time-start_time))
return deco
@timer # 相当于test1=timer(test1)
def test1():
time.sleep(3)
print('in the test1')
@timer
def test2(name):
time.sleep(3)
print('in the test2')
test1() # -->deco
test2('alex',22)
user,passwd='alex','abc123'
def auth(auth_type):
print('auth func:', auth_type)
def outer_wrapper(func):
def wrapper(*args,**kwargs):
username=input('Username:').strip()
password=input('Password:').strip()
if user == username and passwd == password:
print("\033[32;1mUser has passed authentication\033[0m")
res = func(*args,**kwargs)
print("-------after authentication")
return res
else:
print("\033[32;1mInvalid username or password\033[0m")
return wrapper
return outer_wrapper
def index():
print('welcome to index page')
@auth(auth_type='local')
def home():
print('welcome to home page')
return 'from home'
@auth(auth_type='ldap')
def bbs():
print('welcome to bbs page')
index()
print(home())
bbs()
# 列表生成式
a = [1,2,3]
[i*2 for i in range(10)]
# 生成器
# 通过列表生成式,我们可以直接受到内存限制,列表容量肯定是有限的。而且创建一个包含100万个元素的列表,不仅占用很大的内存空间,
# 如果我们仅仅需要访问前面几个元素,那后面绝大多数元素占用的空间都白白浪费了。
# 所以,如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢?这样就不必创建完整的list,从而节省
# 大量的空间。在python中,这种一边循环一边计算的机制,称为生成器:generator
# 要创建一个generator,有很多种方法。第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator:
L = [x*x for x in range(10)]
g = (x*x for x in range(10)) # 这就是列表生成器
# 生成器只记录当前的位置,只有一个__next__()方法,取下一个的含义
def fib(max):
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b # a=b b=a+b
n = n + 1
return 'done'
fib(10)
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b # 将上面程序改成了生成器
a, b = b, a + b # a=b b=a+b
n = n + 1
return '----done----' # 异常时打印的消息
f = fib(10)
print(f.__next__())
print(f.__next__())
print(f.__next__())
print("====start loop====")
for i in f:
print(i)
g = fib(6)
while True:
try:
x = next(g)
print('g:', x)
except StopIteration as e:
print('Generator return value:', e.value)
break
*************************
import time
def consumer(name):
print("%s 准备吃包子啦!" % name)
while True:
baozi = yield
print('包子[%s]来了,被[%s]吃了!' %(baozi, name))
c = consumer('chenronghua')
c.__next__()
# b1 = '韭菜馅'
# c.send(b1)
# c.__next__()
def producer(name):
c = consumer('a')
c2 = consumer('b')
c.__next__()
c2.__next__()
print('开始做包子了!')
for i in range(10):
time.sleep(1)
print('做了一个包子,分两半!')
c.send(i)
c2.send(i)
producer('alex')
# 迭代器
# 可以直接作用于for循环的对象统称为可迭代对象:Iterable
# 可以使用isinstance()判断一个对象是否是Iterable对象
# 可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator
# 可以使用isinstance()判断一个对象是否是Iterator对象
# 内置参数
print(all([0, -5, 3])) # 所有数据为真返回True
any([]) # 有一个数据为真返回True
print(ascii([1, 2, "开外挂"])) # 把对象变为一个字符串
bin(1) # 把数字转二进制
bool(0) # 判断bool值
a = bytes('abc', encoding='utf-8')
b = bytearray('abc', encoding='utf-8')
print(b[0])
print(a.capitalize(), a)
def f():
callable(f) # 返回是否可添加括号
chr(98)
ord('b')
code = 'for i in range(10):print(i)'
c = compile(code, '', 'exec') # 字符串转成可执行程序
exec(c)
exec(code) # 也可以执行
divmod(5, 3) # 相除 余数
def sayhi(n):
print(n)
sayhi(3)
(lambda n: print(n))(5)
calc = lambda n: print(n)
calc(5)
res = filter(lambda n: n > 5, range(10))
for i in res:
print(i)
res1 = map(lambda n: n*2, range(10))
for i in res1:
print(i)
import functools
res2 = functools.reduce(lambda x, y: x+y, range(10))
print(res2)
a = frozenset([1,2,3,4,5,6,4,2]) # 不可变列表
print(globals()) # 展现这个程序的变量值
hash('alex')
hex(11) # 把数据转成16进制
def test():
local_var = 333
print(locals())
print(globals())
test()
print(globals())
print(globals().get('local_var'))
oct(10) # 把数据转成8进制
pow(2, 8) # 返回多少次方
round(1.3342, 2) # 保留2位小数
slice(2, 5) # 切片
a = {6: 2, 8: 0, 1: 4, -5: 6, 99: 11, 4: 22}
print(sorted(a.items())) # 排序
print(sorted(a.items(), key=lambda x: x[1])) # 按值排序
a = [1, 2, 3, 4]
b = ['a', 'b', 'c', 'd']
for i in zip(a, b): # 两个列表打印
print(i)
__import__('decorator') # 当不知道导入模块的时候,可以用名字导入
# 序列化
info = {
'name': 'alex',
'age': 22
}
f = open('test.text', 'w')
f.write(str(info))
f.close()
import json
info = {
'name': 'alex',
'age': 22
}
f = open('test.text', 'w')
f.write(json.dumps(info))
f.close()
# 反序列化
f = open('test.text', 'r')
data = eval(f.read())
f.close()
print(data['age'])
import json
f = open('test.text', 'r')
data = json.loads(f.read())
f.close()
print(data['age'])
# --------------------------------
import pickle
def sayhi(name):
print('hello,', name)
info = {
'name': 'alex',
'age': 22,
'func': sayhi
}
f = open('test.text', 'wb')
f.write(pickle.dumps(info))
f.close()
import pickle
def sayhi(name):
print('hello,', name)
f = open('test.text', 'wb')
f.write(pickle.loads(info))
f.close()
print(data)
---------------------
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 返回当前文件所在的文件夹的上一级文件夹
sys.path.append(BASE_DIR) # 进去目录
from conf import settings # 调用目录下conf文件夹的settings文件
from core import main # 调用目录下core文件夹的main文件