Python: Passing variables between functions

后端 未结 6 1255
庸人自扰
庸人自扰 2020-11-27 11:41

I\'ve spent the past few hours reading around in here and elsewhere, as well as experimenting, but I\'m not really understanding what I am sure is a very basic concept: pass

6条回答
  •  醉梦人生
    2020-11-27 12:43

    This is what is actually happening:

    global_list = []
    
    def defineAList():
        local_list = ['1','2','3']
        print "For checking purposes: in defineAList, list is", local_list 
        return local_list 
    
    def useTheList(passed_list):
        print "For checking purposes: in useTheList, list is", passed_list
    
    def main():
        # returned list is ignored
        returned_list = defineAList()   
    
        # passed_list inside useTheList is set to global_list
        useTheList(global_list) 
    
    main()
    

    This is what you want:

    def defineAList():
        local_list = ['1','2','3']
        print "For checking purposes: in defineAList, list is", local_list 
        return local_list 
    
    def useTheList(passed_list):
        print "For checking purposes: in useTheList, list is", passed_list
    
    def main():
        # returned list is ignored
        returned_list = defineAList()   
    
        # passed_list inside useTheList is set to what is returned from defineAList
        useTheList(returned_list) 
    
    main()
    

    You can even skip the temporary returned_list and pass the returned value directly to useTheList:

    def main():
        # passed_list inside useTheList is set to what is returned from defineAList
        useTheList(defineAList()) 
    

提交回复
热议问题