【问题标题】:Python use Function of a Function inside another FilePython在另一个文件中使用函数的函数
【发布时间】:2018-04-11 12:02:40
【问题描述】:

我有另一个初学者问题,我自己无法找到解决方案,尤其是因为我可能命名错误。

我有两个 python 文件。我需要这样做:

文件一:

def Main():
     def whatever(a,b):
          #do whatever

第二个文件:

Import Main
Main.whatever(str a, str b)

我该怎么做?

【问题讨论】:

  • 你没有。 whatever 是函数 main 的实现细节,如果它在模块中可公开访问,则不会嵌套。
  • 一个内部函数不能在它的作用域之外被访问,除非你从Main返回它。
  • 感谢您的回答。比我该怎么做。 Main 是一个窗口,里面有一个标签。从文件二中,我想在 Main 中设置标签的文本。我如何必须重建我的代码才能访问该标签的代码?

标签: python python-3.x function import


【解决方案1】:

首先,你不是导入这样的函数,而是导入模块。

如果您有一个名为 main.py 的文件包含函数 Main,您可以:

import main
main.Main()

from main import Main
Main()

其次,函数whateverMain中是本地的,退出Main函数后不存在。您可能希望为此使用一个类:

class Main(object):
    def whatever(self, a, b):
        # Do something

然后这样称呼它:

main = Main()
main.whatever(something, something_else)

【讨论】:

  • 你正试图用厨房水槽钉钉子:|
【解决方案2】:

您可以从 Main 返回函数指针并在其他地方使用它。

第一个文件:

def Main():
 def whatever(a,b):
      #do whatever
 return whatever # Return function pointer

第二个文件:

from main import Main
whatever = Main()
whatever(a,b) # Call whatever

【讨论】:

    【解决方案3】:

    test.py

    class Example:
        def printhello():
            print "hello"
    

    其他python文件可以使用这个

    import test
    ex = test.Example()
    

    以后你可以使用ex.printhello()

    from test import printhello
    

    你只能使用printhello()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      相关资源
      最近更新 更多