从外部模块调用类会导致NameError,在IDLE它工作正常 [英] calling class from an external module causes NameError, in IDLE it works fine
问题描述
我在模块中有以下代码:code_database.py
i have the following code in a module called 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)
类定义的方法工作正常:
in idle the class-defined methods work fine:
>>> 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'
>>>
然而,如果我从外部程序调用模块并尝试调用方法, :
however if i call the module from an external program and try to call the methods, they raise a NameError:
import code_database
entry = code_database.Entry()
entry.enter_data()
entry.save_data()
会在终端中导致此情况:
causes this in the terminal:
$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
推荐答案
当您运行 testclass.py
文件时,您正在使用python-2.x。然而,你的代码,似乎是为python-3.x版本。在python-2.x中,你需要使用 raw_input
函数来达到相同的目的,你可以在python-3中使用 input
。X。您可以运行
You're using python-2.x when running your testclass.py
file. Your code, however, seems to be written for python-3.x version. In python-2.x you need to use raw_input
functions for the same purpose you would use input
in python-3.x. You could run
$ python --version
要确定默认使用的是什么版本。
To find out what exactly version you're using by default.
这篇关于从外部模块调用类会导致NameError,在IDLE它工作正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!