python - 在方法之间共享值

标签 python python-3.x return return-value

我以为我知道如何在 Python 中使用 return,但是出现了一些问题,我不明白。

    class Projet(object):
       def pathDirectory(self):
           pathDir= str(QFileDialog.getExistingDirectory(ui.pathTab1, 'Select Path','', QFileDialog.ShowDirsOnly))
           return pathDir

       def goFunc(self, pathDir):

         # do function
         # HERE pathDir is a boolean and not a str with the path directory

   if __name__ == "__main__":
       p = Projet()
       pathDir = p.pathDirectory()
       p.goFunc(pathDir) ## This is the line where it begins

所以我有一个函数可以获取变量中的路径目录并返回它。 我想在其他函数中使用路径目录,但是当我调用它时,它不再是一个字符串,而是一个 bool 值(当我打印时,我得到一个False>路径目录)

更新:抱歉,大家,输入错误,它是pathDir而不是路径,但仍然返回False

最佳答案

这应该有效。您可以创建类的成员变量,而不是传递不必要的变量。该变量可以由任何其他函数更新和重用,而无需担心传递参数。

class Projet(object):

    def pathDirectory(self):
        print "- - in pathDirectory - -"
        self.pathDir= str(QFileDialog.getExistingDirectory(ui.pathTab1, 'Select Path','', QFileDialog.ShowDirsOnly))

    def goFunc(self):
        print "- - In goFunc - -"
        print self.pathDir

if __name__ == "__main__":
    p = Projet()
    p.pathDirectory()
    p.goFunc()

关于python - 在方法之间共享值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30638504/

相关文章:

python - 列表的具体迭代方法

java - 这两种检查数字是否为质数的方法有什么区别?

python - 使用 tensorflow 时 GPU 同步失败

python - python中的求和求和

python - 如何使用带有 gevent 的 redis 或 Python 中的线程来为多个任务构建我的应用程序

jquery - 将数据存储在来自 post jquery 的变量中

c# - 递归,返回后带有 char 数组的 C#

python - 如何从句子中提取名词形容词对

c - 通过 SWIG 输入 Python 3 个字节到 C char*

python - Python 3.5 类型提示是否允许协变返回类型?