2012-12-10 44 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()。