【发布时间】:2014-12-16 08:08:01
【问题描述】:
我制作了一个示例文件,它使用了一个名为Names 的类。它有它的初始化函数和一些方法。当我创建类的实例时,它会检索实例的名字和姓氏。其他方法问候实例并说出离开消息。我的问题是:如何在不运行模块本身的情况下将此文件导入 Python shell?
我的文件名是classNames.py,位置是C:\Users\Darian\Desktop\Python_Programs\Experimenting
我的代码如下所示:
class Names(object):
#first function called when creating an instance of the class
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
#class method that greets the instance of the class.
def intro(self):
print "Hello {} {}!".format(self.first_name, self.last_name)
def departure(self):
print "Goodbye {} {}!".format(self.first_name, self.last_name)
但我得到了错误:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import classNames.py
ImportError: No module named classNames.py
【问题讨论】:
-
正在导入(第一次)正在运行。
-
你的意思是什么我如何将这个文件导入python shell而不需要运行模块本身?
-
“导入而不运行模块”是什么意思?
-
例如,当我运行 shell 时,我可以导入数学库,而无需打开代码并运行它。有没有办法用我的文件做到这一点?我之前在同一个目录中创建了一个新文件并在同一个文件夹中导入了不同的文件时已经这样做了,但那是在 Python IDLE 中。 @BrenBarn
-
请编辑问题以包含(代码格式的)错误消息。简短的回答是 Python 不知道在哪里寻找你的文件。参见例如docs.python.org/2/tutorial/modules.html#the-module-search-path 和 stackoverflow.com/q/12257747/3001761
标签: python class python-2.7