我遇到的一个非常奇怪的python的问题 cs61a lab02

下面是源代码

def cycle(f1, f2, f3):
    """Returns a function that is itself a higher-order function.

    >>> def add1(x):
    ...     return x + 1
    >>> def times2(x):
    ...     return x * 2
    >>> def add3(x):
    ...     return x + 3
    >>> my_cycle = cycle(add1, times2, add3)
    >>> identity = my_cycle(0)
    >>> identity(5)
    5
    >>> add_one_then_double = my_cycle(2)
    >>> add_one_then_double(1)
    4
    >>> do_all_functions = my_cycle(3)
    >>> do_all_functions(2)
    9
    >>> do_more_than_a_cycle = my_cycle(4)
    >>> do_more_than_a_cycle(2)
    10
    >>> do_two_cycles = my_cycle(6)
    >>> do_two_cycles(1)
    19
    """
    "*** YOUR CODE HERE ***"
    def h1(n):
        def h2(x):
            while n > 3:
                x = f3(f2(f1(x)))
                n -= 3
            if n == 0:
                x =x
            elif n == 1:
                x = f1(x)
            elif n == 2:
                x = f2(f1(x))
            elif n == 3:
                x = f3(f2(f1(x)))
            return x
        return h2
    return h1

这样写的话

>>> def add1(x):
...     return x + 1
>>> def times2(x):
...     return x * 2
>>> def add3(x):
...     return x + 3
>>> my_cycle = cycle(add1, times2, add3)
>>> identity = my_cycle(0)
>>> identity(5)

然后会报一个
UnboundLocalError: local variable 'n' referenced before assignment

这样的错误

但是如果改成这样

def cycle(f1, f2, f3):
    """Returns a function that is itself a higher-order function.

    >>> def add1(x):
    ...     return x + 1
    >>> def times2(x):
    ...     return x * 2
    >>> def add3(x):
    ...     return x + 3
    >>> my_cycle = cycle(add1, times2, add3)
    >>> identity = my_cycle(0)
    >>> identity(5)
    5
    >>> add_one_then_double = my_cycle(2)
    >>> add_one_then_double(1)
    4
    >>> do_all_functions = my_cycle(3)
    >>> do_all_functions(2)
    9
    >>> do_more_than_a_cycle = my_cycle(4)
    >>> do_more_than_a_cycle(2)
    10
    >>> do_two_cycles = my_cycle(6)
    >>> do_two_cycles(1)
    19
    """
    "*** YOUR CODE HERE ***"
    def h1(num):
        def h2(x):
            n = num
            while n > 3:
                x = f3(f2(f1(x)))
                n -= 3
            if n == 0:
                x =x
            elif n == 1:
                x = f1(x)
            elif n == 2:
                x = f2(f1(x))
            elif n == 3:
                x = f3(f2(f1(x)))
            return x
        return h2
    return h1

就没有问题,说明在外面函数中定义的这个num是可以拿到的,但是却不可以直接用,最最最奇怪的是,看到答案这么写


    def ret_fn(n):
        def ret(x):
            i = 0
            while i < n:
                if i % 3 == 0:
                    x = f1(x)
                elif i % 3 == 1:
                    x = f2(x)
                else:
                    x = f3(x)
                i += 1
            return x
        return ret
    return ret_fn

这样写没有问题,说明这个n既可以拿到,也可以直接用,我人都傻了

你可能感兴趣的:(python)