简体   繁体   English

在函数与全局变量之间传递变量

[英]Pass variables between functions vs global variables

I have a code with several functions defined which I call from a main container code. 我有一个定义了几个函数的代码,这些代码是从主容器代码中调用的。 Each new function uses variables obtained with the previous functions, so it looks kind of like this: 每个新函数都使用从先前函数获得的变量,因此看起来像这样:

import some_package
import other_package

import first_function as ff
import secon_function as sf
import third_function as tf
import make_plot as mp

# Get values for three variables from first function
var_1, var_2, var_3 = ff()

# Pass some of those values to second function and get some more
var4, var5 = sf(var_1, var_3)

# Same with third function
var_6, var_7, var_8, var_9 = tf(var_2, var_4, var_5)

# Call plotting function with (almost) all variables
mp(var_1, var_2, var_3, var_5, var_6, var_7, var_8, var_9)

Is this more pythonic than using global variables? 这比使用全局变量更具Python性吗? The issue with this methodology is that if I add/remove a new variable from a given function I'm forced to modify four places: the function itself, the call to that function in the main code, the call to the make_plot function in the main and the make_plot function itself. 这种方法的问题在于,如果我从给定的函数中添加/删除新变量,我将不得不修改四个地方:函数本身,在主代码中make_plot函数的调用,对代码中make_plot函数的调用。 main和make_plot函数本身。 Is there a better or more recommended way to do this? 是否有更好或更推荐的方法来做到这一点?

What about putting them in a class? 将它们放在课堂上怎么样?

class Foo(object):
    def ff(self):
        self.var_1, self.var_2, self.var_3 = ff()
    def sf(self):
        self.var_4, self.var_5 = sf(self.var_1, self.var_2)
    def tf(self):
        self.var_6, self.var_7, self.var_8, self.var_9 = tf(self.var_2, self.var_4, self.var_5)
    def plot(self):
        mp(self.var_1, self.var_2, self.var_3, 
           self.var_5, self.var_6, self.var_7, self.var_8, self.var_9)

foo = Foo()
foo.ff()
foo.sf()
foo.tf()
foo.plot()

Maybe some of these methods should be module-level functions that take a Foo instance, maybe some of these attributes should be variables passed around separately, maybe there are really 2, or even 4, different classes here rather than 1, etc. But the idea—you've replaced 9 things to pass around with 1 or 2. 也许其中一些方法应该是采用Foo实例的模块级函数,也许其中一些属性应该是分别传递的变量,也许这里实际上有2个,甚至4个不同的类,而不是1个,等等。想法-您已将9件事替换为1或2。

I'd suggest that what you want is a data structure which is filled in by the various functions and then passed into make_plot at the end. 我建议您想要的是一个数据结构,该数据结构由各种函数填充,然后最后传递给make_plot This largely applies in whatever language you're using. 这在很大程度上适用于您使用的任何语言。

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

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