• 装饰器


    一、
    要求写一个装饰器
    让用户输入用户名和密码
    username
    password
    如果username=’admin‘ 和 密码 = ’123456‘
    再去执行原函数的逻辑
    如果输入错误,不执行原函数,打印 “用户名和密码输入错误”
    def run():
        print('run')
    
    二、
    定义一个deco的类
    用deco类来装饰这个prints函数,
    实现效果,
    1、执行prints函数的内容
    2、把用户名和年龄写入到a.txt文件中(a.txt通过装饰器的参数传入)
    文件保存的内容格式如下
    ben|20
    lili|21
    lucy|22
    
    @deco('a.txt')
    def prints(name, age):
        print('姓名%s, 年龄%s' % (name, age))

    ------------------------答案-----------------------

    一、
    def my_run(func):
        username = input('请输入用户名:')
        while True:
            password = input('请输入密码:')
            if password.isdigit():
                break
            else:
                print('非法字符,请重新输入')
                continue
        def go():
            if username == 'admin' and password == '123456':
                func()
            else:
                print('用户名或密码错误,请重新输入')
        return go
    @my_run
    def run():
        print('登录成功,用户名:admin')
    run()
    
    二、
    class Deco():
        def __call__(self, file):
            self.file = file
            return self.outer
        def outer(self, func):
            self.func = func
            return self.inner
        def inner(self, name, age):
            self.func(name, age)
            with open(self.file, 'a+') as f:
                f.write('%s|%s
    '%(name,age))
    deco = Deco()
    @deco('a.txt')
    def prints(name, age):
        print('姓名%s, 年龄%s' % (name, age))
    prints('ben', 20)
    prints('lili', 19)
    prints('lucy', 21)
  • 相关阅读:
    centos 7 配置 keepalived,主机高可用
    centos 7 安装 nginx
    windows10 设置虚拟网卡/ip
    c#程序以管理员权限运行
    关于js中属性那些事
    centos 7 问题集锦
    几个Git仓库开源软件的比较
    grpc proto3 初体验
    windows下maven安装配置(本地仓库配置)
    navicat premium patch/keygen instruction
  • 原文地址:https://www.cnblogs.com/renshaoqi/p/10182280.html
Copyright © 2020-2023  润新知