Visibility of global variables in imported modules

前端 未结 8 1848
梦毁少年i
梦毁少年i 2020-11-22 11:22

I\'ve run into a bit of a wall importing modules in a Python script. I\'ll do my best to describe the error, why I run into it, and why I\'m tying this particular approach t

8条回答
  •  -上瘾入骨i
    2020-11-22 11:44

    The easiest solution to this particular problem would have been to add another function within the module that would have stored the cursor in a variable global to the module. Then all the other functions could use it as well.

    module1:

    cursor = None
    
    def setCursor(cur):
        global cursor
        cursor = cur
    
    def method(some, args):
        global cursor
        do_stuff(cursor, some, args)
    

    main program:

    import module1
    
    cursor = get_a_cursor()
    module1.setCursor(cursor)
    module1.method()
    

提交回复
热议问题