python装饰器函数练习题
时间: 2023-10-19 21:29:08 浏览: 140
python装饰器练习题及答案
以下是一个关于Python装饰器函数的练习题。
```python
# 需要认证才能执行的装饰器函数
user_status = False
def login(func):
def inner():
_username = "alex"
_password = "abc!23"
global user_status
if user_status is False:
username = input("输入用户名:")
password = input("密码:")
if username == _username and password == _password:
print("welcome login...")
user_status = True
else:
print("wrong username or password!")
if user_status:
func()
return inner
# 示例函数
import time
a = time.localtime()
def log_1():
print('%s-%s-%s'%(a.tm_year, a.tm_mon, a.tm_mday))
def log_2():
time.sleep(2)
print('%s-%s-%s' % (a.tm_year, a.tm_mon, a.tm_mday))
@login
def log_3():
time.sleep(4)
print('%s-%s-%s' % (a.tm_year, a.tm_mon, a.tm_mday))
# 测试代码
log_1()
log_2()
log_3()
```
这个练习题中,我们定义了一个装饰器函数`login`。这个装饰器函数要求在执行被装饰的函数之前进行认证。如果用户没有登录,则要求用户输入用户名和密码进行认证。如果认证成功,则允许执行被装饰的函数,否则提示用户名或密码错误。示例函数`log_1`、`log_2`和`log_3`分别使用了这个装饰器。运行以上代码时,会先执行`log_1`和`log_2`函数,然后会提示输入用户名和密码进行认证。如果认证成功,则执行`log_3`函数,并输出日期信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [python练习题及答案-python装饰器练习题及答案](https://blog.csdn.net/q6q6q/article/details/109341078)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [4道Python装饰器练习题](https://blog.csdn.net/qdPython/article/details/117329802)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文