简体   繁体   English

如何在python中没有全局变量的情况下安全地将代码分为函数

[英]How to safely divide code into functions without global vars in python

It's somewhat too general. 这有点太笼统了。 Suppose I'm writing something long and then I want to cut the code into several small parts with elementary function. 假设我写了很长时间,然后我想用基本功能将代码切成几个小部分。

So the code would be something like: 因此,代码将类似于:

def g():
    # do sth with var1,var2
    pass
def h():
    # do sth with changed var1,var2, and original var3
    pass
def f():
    global var1,var2,var3
    g()
    h()

And in this form, usually, variables are in-place defined or changed in g() or h() . 并且通常以这种形式在g()h()就地定义或更改变量。

As it's warned I should minimize the use of global variables, is there anyway to share (enable in-place/dynamic editing of some vars) data without global statement? 有人警告说,我应该尽量减少使用全局变量,是否有没有全局语句就可以共享(对某些变量进行就地/动态编辑)数据?

Well, actually there're two options, but both require shifting the paradigm from imperative to something else. 好吧,实际上有两种选择,但是都需要将范式从命令式转换为其他。

Create a class, have all those functions be methods of the class, shared vars - the (instance or class-level) attributes - shifts to object-oriented paradigm 创建一个类,使所有这些功能成为该类的方法,共享vars-(实例或类级别的)属性-转换为面向对象的范例

class Something(object):
    def __init__(self, var1_init_val, var2_init_val, var3_init_val):
        self.var1 = var1_init_val
        self.var2 = var2_init_val
        self.var3 = var3_init_val

   def g(self):
       self.var1 = 'qwe'

   def h(self):
       self.var2 = 'asd'

   def f(self):
       self.g()
       self.h()

#use as
something = Something(var1, var2, var3)
something.f()

Make those vars parameters of the function and restructure the code that they are not modified in place - shifts to functional paradigm 设置函数的这些vars参数并重组未修改的代码-转移到函数范式

def g(var1, var2):
    return 'qwe', var2

def h(var1, var2):
    return var1, 'asd'

def f(var1, var2, var3):
    var1, var2 = g(var1, var2)
    var1, var2 = h(var1, var2)  # h here sees "updated" values

# use as
f(var1, var2, var3)

Both examples achieve exactly hte same result - var1 becomes 'qwe', var2 becomes 'asd' and var3 stays unchanged 这两个例子正好达到HTE同样的结果- var1变为“QWE”, var2变成“ASD”和var3保持不变

So, choose your Paradigm :) 因此,选择您的范例:)

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

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