2

我在名为 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)

在空闲时,类定义的方法工作正常:

>>> 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
4

1 回答 1

3

您在运行testclass.py文件时使用的是 python-2.x。但是,您的代码似乎是为 python-3.x 版本编写的。在 python-2.x 中,您需要使用与在 python-3.x 中raw_input相同的目的的函数。input你可以跑

$ python --version

找出您默认使用的确切版本。

于 2010-07-22T14:26:29.417 回答