[英]How can I import a variable from one function to another in Python?
I'm working on a project and I need to import a variable that I got in a function and use it in another one.我正在做一个项目,我需要导入一个在 function 中得到的变量,然后在另一个项目中使用它。 Here's an example of what I'm trying to do.(this is not my code, just an example)这是我正在尝试做的一个例子。(这不是我的代码,只是一个例子)
def interest(day,month,year):
interest = x #I got X by requesting a web data base.
def calc(debt,time):
result = (debt*x)/time
Is there a way to import X from one function to another?有没有办法将 X 从一个 function 导入另一个?
Thanks!谢谢!
Have you considered using a class? 您考虑过上课吗? Classes are extremely useful if you have variables that must be passed around to many functions. 如果必须将变量传递给许多函数,则类非常有用。
class Foo:
def __init__(self):
pass
def set_x(self):
self.x = 5 # Whatever your source is!
def calculate_something(self, foo, bar):
return foo * bar * self.x
q = Foo()
q.set_x()
print(q.calculate_something(2, 3))
Output: 30
输出: 30
In case you aren't interested in using classes you could do the following: 如果您对使用类不感兴趣,可以执行以下操作:
interest
and calc
rather than fetching it within interest
将其传递给interest
和calc
而不是在interest
范围内获取 You don't import variables from a function to another. 您不会将变量从一个函数导入另一个函数。 Functions are for returning values and variables, and you can always call a function to get its return value. 函数用于返回值和变量,您始终可以调用函数以获取其返回值。 For example: 例如:
def interest(amt):
return amt * FIXED_INT
def calc(debt, time):
return debt * interest(debt) ** time
You can pass your variable into arguments 您可以将变量传递给参数
def interest(day,month,year):
interest = x
return interest
def calc(debt,time, interest):
result = (debt*interest)/time
...
x = interest(day,month,year)
calc(debt,time, x)
Here's how I did it: 这是我的操作方式:
def grades_sum(scores):
sum1 = 0
for i in scores:
sum1 = sum1 + i
print sum1
return sum1
grades_sum([100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5])
def grades_average(grades):
average = grades_sum(grades)/float(len(grades))
print average
return average
grades_average([100, 100, 90, 40, 80, 100, 85, 70, 90, 65, 90, 85, 50.5])
Basically, I returned sum1 in the first function, so that when I call it in the second function, sum1 will be divided by float(len(grades)). 基本上,我在第一个函数中返回了sum1,因此当我在第二个函数中调用sum1时,sum1将被float(len(grades))除。 Hope I helped! 希望我能帮上忙! PS Apologies for the ugly formatted text, this is my first post. PS抱歉,格式文本难看,这是我的第一篇文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.