如何从另一个模块执行一个模块的代码?

2024-03-28 10:29:48 发布

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

我知道这是个新问题。但是。我有一个非常简单的模块,其中包含一个类,我想调用该模块从另一个运行。像这样:

#module a, to be imported

import statements

if __name__ == '__main__':

    class a1:
        def __init__(self, stuff):
            do stuff

        def run_proc():
            do stuff involving 'a1' when called from another module

#Module that I'll run, that imports and uses 'a':
if __name__ == '__main__':

    import a

    a.run_proc()

但是,由于其他人可能很明显的原因,我得到了error属性error:'Module'对象没有属性'run\u proc'我是否需要这个类的静态方法,或者在我初始化实例的类中有run\u proc()方法?你知道吗


Tags: 模块runnameimportifthatmaindef
1条回答
网友
1楼 · 发布于 2024-03-28 10:29:48

移动

if __name__ == '__main__':

在模块a中添加到文件的末尾,并添加pass或一些测试代码。你知道吗

你的问题是:

  1. if __name__ == '__main__':范围内的任何东西都只在顶层文件中考虑。你知道吗
  2. 您正在定义一个类,但没有创建一个类实例。你知道吗

模块a,待导入

import statements

class a1:
    def __init__(self, stuff):
        do stuff

    def run_proc():
        #do stuff involving 'a1' when called from another module


if __name__ == '__main__':
    pass # Replace with test code!

我将运行的、导入并使用“a”的模块:

import a
def do_a():
    A = a.a1()   # Create an instance
    A.run_proc() # Use it

if __name__ == '__main__':
   do_a()

相关问题 更多 >