从外部模块调用类导致NameError,在IDLE中正常工作
我在一个叫做 code_database.py 的模块里写了以下代码:
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)
在 IDLE 里,定义的类方法运行得很好:
>>> 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
1 个回答
3
你在运行你的 testclass.py
文件时使用的是 python-2.x 版本。不过,你的代码看起来是为 python-3.x 版本写的。在 python-2.x 中,你需要用 raw_input
函数来实现和 python-3.x 中 input
函数相同的功能。你可以运行
$ python --version
来查看你默认使用的具体版本是什么。