相关疑难解决方法(0)

是否可以在python中修改外部但不是全局范围的变量?

给出以下代码:

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在外部作用域中,但不在全局作用域中.是否可以bB()函数内修改变量?当然我可以从这里读取它print(),但是如何修改呢?

python python-2.7

95
推荐指数
3
解决办法
5万
查看次数

带参数的 Python3“重复”装饰器:@repeat(n)

我看过(很多)带有和不带参数的装饰器的教程和片段,包括我认为是规范答案的那两个:带有参数的装饰器带有 @ 语法的 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)

python default-parameters python-3.x python-decorators

3
推荐指数
1
解决办法
3534
查看次数