Python学习笔记(十):

  1. 装饰器的应用
  2. 列表生成式
  3. 生成器
  4. 迭代器
  5. 模块:time,random

1. 装饰器的应用-登陆练习

login_status = False    # 定义登陆状态
def type(auth_type):    # 装饰器传参函数
    def login(fucn):    # 装饰器函数
        def inner():    # 附加功能
            global login_status     # 将登陆状态变量变为全局变量
            if login_status == False:
                if auth_type == 'jingdong':
                    username = input('username:')
                    password = input('password:')
                    with open('jingdong.txt','r') as f:
                        lines = f.readlines()
                        for i in lines:
                            i = eval(i)
                            if username in i and password == i[username]:
                                print('welcome %s' % (username))
                                login_status = True
                                fucn()
                            else:
                                print('wrong username or password')
                elif auth_type == 'weixin':
                    username = input('username:')
                    password = input('password:')
                    with open('weixin.txt', 'r') as f:
                        lines = f.readlines()
                        for i in lines:
                            i = eval(i)
                            if username in i and password == i[username]:
                                print('welcome %s' % (username))
                                login_status = True
                                fucn()
                            else:
                                print('wrong username or password')
            else:
                pass
        return inner
    return login

@type('jingdong')   # 连接装饰器
def home():         # 功能函数
    print('welcome to home page')

@type('weixin')
def finance():
    print('welcome to finance page')

@type('jingdong')
def book():
    print('welcome to book page')


if __name__ == '__main__':

    while True:
        print('welcome to JD:')
        print('choice 1 to home')
        print('choice 2 to finance')
        print('choice 3 to book')
        print('choice 0 to back')
        choice = input('Where are you going:')
        if choice == '1':
            home()
        elif choice == '2':
            finance()
        elif choice == '3':
            book()
        elif choice == '0':
            break

2. 列表生成式

代码示例:

a = [x for x in range(10)]
print(a)    # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

a = [x*2 for x in range(10)]
print(a)    # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

def f(n):
    return n**3

a = [f(x) for x in range(10)]
print(a)    # [0, 1, 8, 27, 64, 125, 216, 343, 512, 729]

3. 生成器

代码示例:

# 第一种方法
s = (x for x in range(100)) # 生成器
# for的作用:消除内存占用,判断遍历完成
for i in s:
    print(i)
# 第二种方法
def foo():
    i = range(22)
    yield i

for i in foo():
    print(i)
# send方法给yield赋值
def bar():
    print('ok1')
    count = yield 1 # 接收'ee'
    print(count)
    print('ok2')
    yield 2

b = bar()
b.send(None)    # 相当于next(b)
b.send('ee')    # 将'ee'赋值给第一个yield

4. 迭代器

  • 生成器都是迭代器
    什么是迭代器?
  1. 有iter方法
  2. 有next方法

5. 模块

1. time模块

函数/方法:
time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone

代码示例:

print(time.strftime('%Y-%m-%d  %H:%M:%S'))  #2017-09-20  13:44:01

print(time.strptime('2017-09-20  12:53:21','%Y-%m-%d  %H:%M:%S'))
# time.struct_time(tm_year=2017, tm_mon=9, tm_mday=20, tm_hour=12, tm_min=53, tm_sec=21, tm_wday=2, tm_yday=263, tm_isdst=-1)

2. random模块

print(random.randint(1,8))      # 从1-8中随机取值
print(random.choice('hello'))   # 从‘hello’中随机取一个字母
# 实现验证码
def v_code():
    code = ''
    for i in range(5):
        add = random.choice([random.randrange(10),chr(random.randrange(65,91))])
        code += str(add)
    print(code)

v_code()