2010-07-22 22 views
2

我有一個模塊在下面的代碼名爲code_database.py調用類引起NameError,在空閒時,其工作正常

class Entry(): 
    def enter_data(self): 
     self.title = input('enter a title: ') 
     print('enter the code, press ctrl-d to end: ') 
     self.code = sys.stdin.readlines() 
     self.tags = input('enter tags: ') 

    def save_data(self): 
     with open('entry.pickle2', 'ab') as f: 
      pickle.dump(self, f) 
在空閒

類定義的方法做工精細:

>>> import code_database 
>>> entry = code_database.Entry() 
>>> entry.enter_data() 
enter a title: a 
enter the code, press ctrl-d to end: 
benter tags: c 
>>> entry.title 
'a' 
>>> entry.code 
['b'] 
>>> entry.tags 
'c' 
>>> 

但是如果我從一個外部程序調用模塊,並嘗試調用的方法,它們引發NameError:

import code_database 

    entry = code_database.Entry() 
    entry.enter_data() 
    entry.save_data() 

這導致在終端:

$python testclass.py 
enter a title: mo 
Traceback (most recent call last): 
    File "testclass.py", line 6, in <module> 
    entry.enter_data() 
    File "/home/mo/python/projects/code_database/code_database.py", line 8, in enter_data 
    self.title = input('enter a title: ') 
    File "<string>", line 1, in <module> 
NameError: name 'mo' is not defined 

回答

3

運行您testclass.py文件,當你使用python-2.x的。然而,你的代碼似乎是爲python-3.x版本編寫的。在python-2.x中,您需要使用raw_input函數來達到與python-3.x中的input相同的目的。您可以運行

$ python --version 

要了解您默認使用的是什麼版本。

+0

哈哈,今天沒有足夠的咖啡我猜...這是一聲巨響。 – momo 2010-07-22 14:30:41

相關問題