简体   繁体   English

Python - 如何从其他脚本中的函数返回值

[英]Python - how to return values from function in other script

I want to return a value in a script MAIN.py where the function is stated in another script?我想在脚本 MAIN.py 中返回一个值,其中该函数在另一个脚本中声明? How do I do this?我该怎么做呢?

In a function SUB.py I have defined:在函数 SUB.py 中,我定义了:

def SUM_POWER(a,b):
    c = a+b
    d = a**b
    return [c,d]

Now I want to get in a script MAIN.py: c and d for a=3 and b=4.现在我想进入一个脚本 MAIN.py: c and d for a=3 and b=4。 I tried in MAIN.py:我在 MAIN.py 中尝试过:

import SUB
c,d = SUM_POWER(3,4)

What do I do wrong?我做错了什么? Preferably I would want to name the variables in MAIN.py different than c,d.最好我想在 MAIN.py 中命名不同于 c,d 的变量。 So for example out1, out2.所以例如out1,out2。 out1 has to correspond to c and out2 corresponds to d by the order in which the values are returned.按照返回值的顺序,out1 必须对应于 c,out2 对应于 d。

The problem is in function call, as well as that you are returning a list while trying to store it in a tuple.问题在于函数调用,以及您在尝试将列表存储在元组中时返回列表。

Try this SUB.py -试试这个 SUB.py -

def SUM_POWER(a,b):
c = a+b
d = a**b
return c,d

MAIN.py -主要.py -

import SUB
c,d = SUB.SUM_POWER(3,4)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM