简体   繁体   English

Python在If-Else语句的Else块中重用变量

[英]Python Reuse a Variable in the Else Block of an If-Else Statement

I'm currently working on a simple file transfer program in Python. 我目前正在使用Python开发一个简单的文件传输程序。 I am having trouble with the function for prompting the user for the location of the folder to be copied. 我在提示用户输入要复制的文件夹的位置时遇到麻烦。

def getSrc():
    if getSrc.has_been_called is False:
        source = askdirectory()
        getSrc.has_been_called = True
        return source
    else:
        return source

getSrc.has_been_called = False

The variable source comes up as an unresolved reference. 可变来源作为未解决的参考出现。 I understand that the variable must be initialized again due to the scope of an if-else statement, but I am unsure of how to save the directory in the source variable without the user being prompted for the directory again. 我了解,由于if-else语句的作用域,必须再次初始化变量,但是我不确定如何在不提示用户再次输入目录的情况下将目录保存在源变量中。

When you call getSrc a second time, the value of source that was created the first time has long since gone out of scope and been garbage collected. 第二次调用getSrc时,第一次创建的source的值已经超出范围并被垃圾回收。 To prevent this, try making source an attribute of the function the same way you did for has_been_called . 为了防止这种情况,请尝试source功能的你做了相同的方法,属性has_been_called

def getSrc():
    if getSrc.has_been_called is False:
        getSrc.source = askdirectory()
        getSrc.has_been_called = True
        return getSrc.source
    else:
        return getSrc.source

Although, it's a bit messy to have two attributes when you can make do with one: 虽然,当您可以使用两个属性时有点混乱:

def getSrc():
    if not getSrc.source:
        getSrc.source = askdirectory()
    return getSrc.source
getSrc.source = None

If you're in a higher-order functional mood, it may be worthwhile to create a function that memoizes other functions. 如果您处于较高阶的功能状态,则可能值得创建一个记忆其他功能的功能。 You can look at PythonDecoratorLibrary for some tips on doing that, or you can just use one already prepared by Python 您可以查看PythonDecoratorLibrary上的一些提示,也可以仅使用Python已经准备好的一个提示

import functools

@functools.lru_cache()
def getSrc():
    return askdirectory()

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

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