Python在另一个Fi中使用函数的函数

2024-04-26 20:40:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我还有一个初学者的问题,我无法找到自己的解决办法,特别是因为我可能会名称错误的事情。你知道吗

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

文件一:

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

第二个文件:

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

我该怎么做?你知道吗


Tags: 文件import名称maindef错误事情do
3条回答

首先,不是像那样导入函数,而是导入模块。你知道吗

如果有一个名为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)

你知道吗测试.py你知道吗

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

其他python文件可以使用这个

import test
ex = test.Example()

稍后您可以使用ex.printhello()

或者

from test import printhello

只能使用printhello()

您可以从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

相关问题 更多 >