给出以下代码:
def A() :
b = 1
def B() :
# I can access 'b' from here.
print( b )
# But can i modify 'b' here? 'global' and assignment will not work.
B()
A()
Run Code Online (Sandbox Code Playgroud)
对于B()函数变量中的代码,b在外部作用域中,但不在全局作用域中.是否可以b从B()函数内修改变量?当然我可以从这里读取它print(),但是如何修改呢?
我看过(很多)带有和不带参数的装饰器的教程和片段,包括我认为是规范答案的那两个:带有参数的装饰器、带有 @ 语法的 python 装饰器参数,但我不明白为什么我的代码出现错误。
以下代码位于文件中decorators.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Description: decorators
"""
import functools
def repeat(nbrTimes=2):
'''
Define parametrized decorator with arguments
Default nbr of repeats is 2
'''
def real_repeat(func):
"""
Repeats execution 'nbrTimes' times
"""
@functools.wraps(func)
def wrapper_repeat(*args, **kwargs):
while nbrTimes != 0:
nbrTimes -= 1
return func(*args, **kwargs)
return wrapper_repeat
return real_repeat
Run Code Online (Sandbox Code Playgroud)
我从语法检查器得到的第一个警告是nbrTimes“未使用的参数”。
我在 python3 交互式控制台中测试了上述内容:
>>> from decorators import repeat
>>> @repeat(nbrTimes=3)
>>> …Run Code Online (Sandbox Code Playgroud)