Given this module (sample.py):
def calculation(x):
r = x + 1
return r
In my main .py file in Spyder, I'm calling it like this:
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?
I want to continue by doing something like:
a = r/2
in the main .py file after calling
sample.calculation(2)
Update:
I would assume b would result in the number 3. But what if the module returns 2 different numbers (objects)? 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?
You use that b
variable you assigned the value to.
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. A function ends as soon as it executes a 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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.