在Python中是否有时间在类中使用全局变量?

时间:2014-05-08 14:44:36

标签: python class variables global

只是一个简单的语义问题。我正在一个类中编写一个简单的函数:

class TheClass:

    def __init__():
         self.variable = 0


    def function(self):
        if self.variable == 9:
            #do these things
             self.variable = 0
        elif self.variable > 9:
            self.variable += 1
            #do these things until its time to
            #do the other stuff

目前我编写代码时有很多这样的函数,我需要一个简单的迭代器 可以计算函数运行的次数。不过我觉得这很草率 编写这样的东西的方法。当我拥有许多需要这样一个变量的函数时,它就会变得很糟糕。

我可以想象的另一种方法是添加全局标记。像下面的代码。还有更好的方法吗?

def function:
    global variable
    if variable == 9:
        #do these things
         variable = 0
    elif variable > 9:
        #do this other stuff
        variable +=1

1 个答案:

答案 0 :(得分:0)

我已经做了十多年的python,我永远找不到使用全局的有效用例。我最接近的是在模块级别构建singleton,就像log实例一样。

返回您的代码:

def function:
    global variable
    if variable == 9:
        #do these things
         variable = 0
    elif variable > 9:
        #do this other stuff
        variable +=1

我认为做这样的事情没有任何好处。将变量设置为全局使得很难知道和分析程序中变量的生命周期,使其难以调试。如果它们使用相同的名称,您可以在其他函数中遇到其他问题,例如阴影。

Python已被构建为OOP,并帮助设计OOP算法。您的以下代码可能看起来有点冗长:

class TheClass:
    def __init__():
         self.variable = 0

    def method(self):
        if self.variable == 9:
            #do these things
             self.variable = 0
        elif self.variable > 9:
            self.variable += 1
            #do these things until its time to
            #do the other stuff

但它有助于构建正确的算法。因为变量不会出现,但它被绑定并封装在TheClass实例中,所以当你使用它时你会这样做:

foo = TheClass()
foo.method()

如果您发现对于像您这样简单的算法来说过于冗长,那么您可以简单地将变量设为参数:

def function(variable):
    if variable == 9:
        #do these things
        variable = 0
    elif variable > 9:
        variable += 1
        #do these things until its time to
        #do the other stuff
    return variable

然后:

modified_foo = function(original_foo)

最后,另一种方法是在函数上使用闭包:

def other_function():
    variable = 0
    def function():
        if variable == 9:
            #do these things
            variable = 0
        elif variable > 9:
            variable += 1
            #do these things until its time to
            #do the other stuff

    # variable has not been modified
    function()
    # variable has been modified

这不是最好的方法,但最好将变量的范围限制在other_function()的范围内。