Pythonic维护变量赋值的方法

时间:2015-12-18 05:00:50

标签: python python-3.x

我之前正在编写一个小文件实用程序,并且遇到了通过引用传递的问题。在阅读How do I pass a variable by reference?之后,我将我想要传递的变量设置为参数,并将其设置为返回值。在下面的代码中,它是行:

diff = compareDir(path0, path0List, path1, path1List, diff)

其中diff是我希望通过引用传递的变量。

虽然这有效,但感觉相当尴尬。我认为必须有更好的方法。在许多其他语言中,我可以将compareLists()设置为没有返回值,并使用修改pass-by-reference参数的副作用。 Python的pass-by-assignment似乎不允许这样做。

我对python比较陌生,想知道是否有更多的pythonic方法来解决我的问题。是否需要完全重新考虑这些功能?或者有一个我不知道的好声明?我想远离全局变量。

我欢迎任何建设性的批评和评论。谢谢!

相关守则:

def comparePaths(path0, path1):
    path0List = os.listdir(path0)
    path1List = os.listdir(path1)

    diff = False
    diff = compareDir(path0, path0List, path1, path1List, diff)
    print()
    diff = compareDir(path1, path1List, path0, path0List, diff)
    return diff

def compareDir(basePath, baseList, comparePath, compareDir, diffVar):
    for entry in baseList:
        #compare to the other folder
        if (not (entry in compareDir)):
            if (not (diffVar)):
                diffVar = True
                print ("Discreptancies found. The following files are different:")
                print (str(entry) + " doesn\'t exist in " + str(comparePath))
            else:
                print (str(entry) + " doesn\'t exist in " + str(comparePath))
    return diffVar

2 个答案:

答案 0 :(得分:3)

因为在Python中,bool类型根据定义是不可变的,所以修改函数内部的bool变量而不重新分配它(并且不将其定义为全局变量)的唯一方法是将其存储在可变类型实例中。即:

  • 将其存储在可变数据结构(list,dict,...)中,并将此数据结构传递给函数。
  • 将其作为可变对象的属性,并将此对象传递给函数。

答案 1 :(得分:2)

您的问题有多种可能的解决方案。

您可以在python3之前添加nonlocal修饰符(global),以便从内部函数进行修改并从外部可以看到更改。

    diff = False

    def compareDir(basePath, baseList, comparePath, compareDir):
        nonlocal diff
        for entry in baseList:
                    ...
                    diff = True

    compareDir(path0, path0List, path1, path1List)
    print()
    compareDir(path1, path1List, path0, path0List)
    return diff

或者你可以使用differ对象和self.diff作为该对象的显式状态的OOP解决方案。

class differ(object):
    def __init__(self):
        self.diff = False
    def compareDir(self, basePath, baseList, comparePath, compareDir):
        ...
              self.diff = True
        ...

    def comparePaths(self, path0, path1):

如果你需要在某些情境中做很多工作,那么后期解决方案会非常有用。并且经常需要改变共享状态。