Why doesn't this closure modify the variable in the enclosing scope?

后端 未结 4 952
-上瘾入骨i
-上瘾入骨i 2020-12-15 05:59

This bit of Python does not work:

def make_incrementer(start):
    def closure():
        # I know I could write \'x = start\' and use x - that\'s not my poi         


        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-15 06:36

    In Python 3.x you can use the nonlocal keyword to rebind names not in the local scope. In 2.x your only options are modifying (or mutating) the closure variables, adding instance variables to the inner function, or (as you don't want to do) creating a local variable...

    # modifying  --> call like x = make_incrementer([100])
    def make_incrementer(start):
        def closure():
            # I know I could write 'x = start' and use x - that's not my point though (:
            while True:
                yield start[0]
                start[0] += 1
        return closure
    
    # adding instance variables  --> call like x = make_incrementer(100)
    def make_incrementer(start):
        def closure():
            while True:
                yield closure.start
                closure.start += 1
        closure.start = start
        return closure
    
    # creating local variable  --> call like x = make_incrementer(100)
    def make_incrementer(start):
        def closure(start=start):
            while True:
                yield start
                start += 1
        return closure
    

提交回复
热议问题