Python 从被调用模块获取返回对象
Python Get Returned Object From Called Module
鉴于此模块 (sample.py):
def calculation(x):
r = x + 1
return r
在 Spyder 的主要 .py 文件中,我这样称呼它:
import sample
b = sample.calculation(2)
我的(愚蠢的)问题是:
如何访问示例模块中定义的 r,以便在我调用示例的主 .py 文件中进行其他计算?
我想继续做类似的事情:
a = r/2
调用后在主 .py 文件中
sample.calculation(2)
更新:
我假设 b 会导致数字 3。
但是如果模块 returns 2 个不同的数字(对象)呢?我如何单独访问它们?
My (dumb) question is: how to I access r, as defined in the sample module, for other calculations in the main .py file from which I'm calling sample?
您使用您为其赋值的 b
变量。
But what if the module returns 2 different numbers (objects)? How do I access them individually?
如果你的意思是函数这样做:
def return_two_things():
return 1, 2
然后将它们分配给两个变量:
a, b = module.return_two_things()
如果你的意思是函数这样做:
def wrong_way():
return 1
return 2
那么你的函数是错误的,你误解了 return
语句的工作原理。函数在执行 return
后立即结束;它不会继续return更多的事情。
通过将其设置为全局变量可以访问另一个模块的变量。但这不是一个好的做法,而且经常被避免。你可以这样做
import sample
r = sample.calculation(2)
这样,您可以使用相同的变量名 'r' 但它现在是局部变量。
关于从模块返回多个对象的第二个问题,你可以这样做
def module1(x):
return x+1,x+2
a,b = module1(5)
#a has 5+1 = 6
#b has 5+2 = 7
鉴于此模块 (sample.py):
def calculation(x):
r = x + 1
return r
在 Spyder 的主要 .py 文件中,我这样称呼它:
import sample
b = sample.calculation(2)
我的(愚蠢的)问题是: 如何访问示例模块中定义的 r,以便在我调用示例的主 .py 文件中进行其他计算?
我想继续做类似的事情:
a = r/2
调用后在主 .py 文件中
sample.calculation(2)
更新:
我假设 b 会导致数字 3。 但是如果模块 returns 2 个不同的数字(对象)呢?我如何单独访问它们?
My (dumb) question is: how to I access r, as defined in the sample module, for other calculations in the main .py file from which I'm calling sample?
您使用您为其赋值的 b
变量。
But what if the module returns 2 different numbers (objects)? How do I access them individually?
如果你的意思是函数这样做:
def return_two_things():
return 1, 2
然后将它们分配给两个变量:
a, b = module.return_two_things()
如果你的意思是函数这样做:
def wrong_way():
return 1
return 2
那么你的函数是错误的,你误解了 return
语句的工作原理。函数在执行 return
后立即结束;它不会继续return更多的事情。
通过将其设置为全局变量可以访问另一个模块的变量。但这不是一个好的做法,而且经常被避免。你可以这样做
import sample
r = sample.calculation(2)
这样,您可以使用相同的变量名 'r' 但它现在是局部变量。
关于从模块返回多个对象的第二个问题,你可以这样做
def module1(x):
return x+1,x+2
a,b = module1(5)
#a has 5+1 = 6
#b has 5+2 = 7