Python expose to scope

Let's consider we have a module called mod which has a function func . I want to import the module and run func, exposing a variable var to its scope.

a.func() # and func can do stuff with var

How can i do this?


您可以将var定义到的模块导入您的mod模块,或者将var作为参数传递给func()


Pass the variable to the function. Works the same across modules as it does in a single module.

# module a
def func(v):
    print v

# module b
import a
var=42
a.func(var)

If you need to modify the value, return it. The caller then can put it wherever they want, including back into the same variable.

# module a
def func(v):
    return v + 1

# module b
import a
var=42
var = a.func(var)   # var is now 43

Some objects, such as lists, are mutable and can be changed by the function. You don't have to return those. Sometimes it is convenient to return them, but I'll show it without.

# module a
def func(v):
    v.append(42)

# module b
import a
var=[]        # empty list
a.func(var)   # var is now [42]

Most likely, you should add an argument to func() through which to pass in the variable var. If you want func() to modify var, then have the function return the new value. (If necessary you can easily have multiple return values).

链接地址: http://www.djcxy.com/p/53142.html

上一篇: cpython和python有什么区别吗?

下一篇: Python暴露于范围