2013-08-06 33 views
0

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

#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() 

然而,对于可能明显其它方面的原因,我得到的错误属性错误:“模块”对象有没有属性“run_proc”我需要为这个类的静态方法,或在类中有我的run_proc()方法,我初始化了一个实例?

+0

你知道怎么班蟒蛇工作? –

+2

**为什么**对于上帝的爱是否有主哨内的班级定义? –

+1

不要在main中定义类。 – zhangyangyu

回答

4

在模块移动

if __name__ == '__main__': 

到文件的末尾,并添加通或一些测试代码。

你的问题是:

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

模块,需要进口

,我会跑
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() 
+0

就像我怀疑的一样。感谢您的建设性帮助。 – StatsViaCsh

相关问题