2012-12-10 41 views
0

另一个类对象我有一个程序名“new.py”与“:访问通过进口

class hello: 

    def __init__(self, summary): 
     self.summary = summary 


    def hi(self): 
     print self.summary 

if __name__ == "__main__": 
    h = hello(summary = "this is a hello program") 
    h.hi() 

当我要进入功能喜到另一个程序名称another.py,那么我不能够访问功能..请帮助我,纠正我也... another.py:

import new 

    class another: 

     def __init__(self, value): 
      self.value = value 

     def show(self): 
      print "value is %s" % self.value 
      new.hi() 
      print "done" 

    if __name__ == "__main__": 
     a = another(value = "this is a another value") 
     a.show() 

OUTPUT:

new.hi() 
AttributeError: 'module' object has no attribute hi 
+1

您需要在'another.py'中定义'hello'的实例。 'new.hi'没有定义,但是'new.hello'。 – Alex

+0

对不起,但仍然显示错误:全球名称“新”未定义“...我试图从新导入你好 –

回答

4

问题是您没有初始化hello对象。所以,你需要调用喜函数之前做到这一点的地方:

 n = new.hello('some string') 

那么你可以拨打:

 n.hi() 
+0

与初始化我们不能用”导入“模块名称做的初始化你好对象.. –

+0

对不起,我不'不知道你的意思。 –

0

实际的问题是你做的事:

import new 

,然后:

new.hi() 

hi()is not defi ned in new,它在new.hello中定义,这是你的类。 您需要创建类hello的新实例并从那里调用hi()。