如何将文件导入到Python shell中?

2024-04-26 12:45:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我制作了一个使用名为Names的类的示例文件。它具有初始化功能和一些方法。当我创建类的实例时,它会检索实例的名字和姓氏。其他方法向实例打招呼并发出离开消息。我的问题是:如何将这个文件导入到Python shell中,而不必运行模块本身?

我的文件名是classNames.py,位置是C:\Users\Darian\Desktop\Python\u Programs\expericing

下面是我的代码:

 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

Tags: 文件ofthe实例方法instancenamepy
1条回答
网友
1楼 · 发布于 2024-04-26 12:45:49

我不清楚您期望的是什么,看到的是什么,但是对您的模块的处理与math和任何其他模块的处理完全一样:

你只需要导入它们。如果这是第一次发生,则会获取并执行文件。运行后留在名称空间中的所有内容都可以从外部获得。

如果您的代码只包含defclass语句和赋值,就不会注意到任何事情发生,因为,好吧,此时没有“真正的”事情发生。但是您可以使用类、函数和其他名称。

但是,如果您在顶层有print语句,您将看到它确实被执行了。

如果这个文件位于Python路径的任何地方(显式地或者因为它在当前工作目录中),可以像

import classNames

并使用其内容,例如

n = classNames.Names("John", "Doe")

或者是你

from classNames import Names
n = Names("John", "Doe")

不要执行import classNames.py,因为这将尝试从包classNames/导入模块py.py

相关问题 更多 >