我之前正在编写一个小文件实用程序,并且通过引用传递了一个问题.阅读后如何通过引用传递变量?,我将我想要传递的变量设置为参数,并将其设置为返回值.在下面的代码中,它是行:
diff = compareDir(path0, path0List, path1, path1List, diff)
Run Code Online (Sandbox Code Playgroud)
其中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:") …Run Code Online (Sandbox Code Playgroud)