[英]Python Get Returned Object From Called Module
Given this module (sample.py): 鉴于此模块(sample.py):
def calculation(x):
r = x + 1
return r
In my main .py file in Spyder, I'm calling it like this: 在Spyder的主要.py文件中,我这样称呼它:
import sample
b = sample.calculation(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? 我的(愚蠢的)问题是:如何访问样本模块中定义的r,以便从中调用样本的主.py文件中的其他计算?
I want to continue by doing something like: 我想继续做类似的事情:
a = r/2
in the main .py file after calling 调用后在主.py文件中
sample.calculation(2)
Update: 更新:
I would assume b would result in the number 3. But what if the module returns 2 different numbers (objects)? 我假设b会导致数字3。但是,如果模块返回2个不同的数字(对象),该怎么办? How do I access them individually?
如何单独访问它们?
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?
我的(愚蠢的)问题是:如何访问样本模块中定义的r,以便从中调用样本的主.py文件中的其他计算?
You use that b
variable you assigned the value to. 您可以使用为其分配值的
b
变量。
But what if the module returns 2 different numbers (objects)?
但是,如果模块返回两个不同的数字(对象)怎么办? How do I access them individually?
如何单独访问它们?
If you mean the function does this: 如果您的意思是该函数执行此操作:
def return_two_things():
return 1, 2
then you assign them to two variables: 然后将它们分配给两个变量:
a, b = module.return_two_things()
If you mean the function does this: 如果您的意思是该函数执行此操作:
def wrong_way():
return 1
return 2
then your function is wrong, and you have misunderstood how return
statements work. 则您的函数是错误的,并且您误解了
return
语句的工作方式。 A function ends as soon as it executes a return
; 函数一执行
return
就结束; it does not continue on to return more things. 它不会继续返回更多的东西。
Accessing another module's variable is possible by making it global. 通过全局访问另一个模块的变量是可能的。 But it is not a good practice and often avoided.
但这不是一个好习惯,并且经常避免。 You can do this instead
你可以这样做
import sample
r = sample.calculation(2)
This way, you can use the same variable name 'r' but it is now a local variable. 这样,您可以使用相同的变量名“ r”,但现在它是一个局部变量。
For your second question about returning multiple objects from a module, you can do this 关于从模块返回多个对象的第二个问题,您可以执行此操作
def module1(x):
return x+1,x+2
a,b = module1(5)
#a has 5+1 = 6
#b has 5+2 = 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.