从外部模块调用类会导致 NameError,在 IDLE 中它工作正常

2023-12-27

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

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

$ python --version

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从外部模块调用类会导致 NameError,在 IDLE 中它工作正常 的相关文章

随机推荐