且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Python中将变量从一个函数导入到另一个函数?

更新时间:2021-12-05 21:38:24

您是否考虑过使用类?如果必须将变量传递给许多函数,则类非常有用.

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:

  1. 获取x.
  2. 将其传递给interestcalc,而不是在interest
  3. 中获取
  1. Fetch x.
  2. Pass it to both interest and calc rather than fetching it within interest