如何在Python中将变量从一个函数导入到另一个函数? [英] How can I import a variable from one function to another in Python?
本文介绍了如何在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. 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
是否可以将X从一个函数导入到另一个函数?
Is there a way to import X from one function to another?
谢谢!
推荐答案
您是否考虑过使用类?如果必须将变量传递给许多函数,则类非常有用.
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))
输出:30
如果您对使用类不感兴趣,可以执行以下操作:
In case you aren't interested in using classes you could do the following:
- 获取x.
- 将其传递给
interest
和calc
,而不是在interest
中获取
- Fetch x.
- Pass it to both
interest
andcalc
rather than fetching it withininterest
这篇关于如何在Python中将变量从一个函数导入到另一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文