注册 登录
编程论坛 Python论坛

外层函数的变量能不能直接被嵌套函数引用计算?

troyzyc 发布于 2018-09-01 19:08, 1304 次点击
示例1:fun1()函数中的b不能在fun2()中直接用吗?
class Solution:
    def fun1(self,a,b):
        c = a + b
        b = 0         #fun1()函数中的b不能在fun2()中直接用吗?
        def fun2(c):
            b += 1      #报错:UnboundLocalError: local variable 'b' referenced before assignment
            print('b=',b)
            print('c=',c)
            return
        
        fun2(c)
        print(b)
        return 0
   
result = Solution()
result.fun1(1,2)

示例2:但是下边程序中Permutation(self, ss)中的lens变量却能直接在dfs函数中使用,这是为什么?
class Solution:   
    def Permutation(self, ss):  
        lens = len(ss)    #该变量具有全局性,在dfs中可以直接用。
        box = [0] * lens  
        book =[0] * lens  
        steps = 0     
        ans = []           
        if len(ss) == 0:  
            return []
        def dfs(steps):
            if steps > lens-1:    #重点:Permutation的变量lens可以直接在dfs中应用
                str1 = ''        
                for j in range(lens):  
                    #print("{0}".format(box[j]),end='')
                #print('\n')
                    str1 = str1 + box[j]   
                ans.append(str1)
               
                return
            
            for i in range(lens):      
                if book[i] == 0 :   
                    box[steps] = ss[i]
                    book[i] = 1      

                    dfs(steps + 1)   #递归
                    book[i] = 0  
            return
            
        dfs(steps)  #函数中若要调用嵌套函数,需要引用这个函数
        
        #在dfs及自身的递归结束后,输出列表ans
        #特殊情况2:ss=['a','a'],有重复的字母时,要用去重
        ans = list(set(ans))   #去重:set去重后返回的是set类型,要改为list类型
        ans = sorted(ans)      #再对ans结果排序,从小到大
        print(ans)
        return ans
        
        
ss = ['a','b','c']
result = Solution()
result.Permutation(ss)  
1 回复
#2
kfyniriu2018-09-05 17:37
两个函数分别加上 global b
1