简体   繁体   English

如何将文件导入Python Shell?

[英]How do you import files into the Python shell?

I made a sample file that uses a class called Names . 我制作了一个使用名为Names的类的示例文件。 It has its initialization function and a few methods. 它具有其初始化功能和一些方法。 When I create an instance of the class it retrieves the instance's first name and last name. 当我创建该类的实例时,它将检索该实例的名字和姓氏。 The other methods greet the instance and say a departure message. 其他方法向实例打招呼并说出离开消息。 My question is: how do I import this file into the Python shell without having to run the module itself? 我的问题是:如何在不运行模块本身的情况下将该文件导入Python Shell?

The name of my file is classNames.py and the location is C:\\Users\\Darian\\Desktop\\Python_Programs\\Experimenting 我的文件名为classNames.py,位置为C:\\ Users \\ Darian \\ Desktop \\ Python_Programs \\ Experimenting

Here is what my code looks like: 这是我的代码:

 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)

But I get the error: 但是我得到了错误:

Traceback (most recent call last): 
  File "<pyshell#0>", line 1, in <module> 
    import classNames.py 
ImportError: No module named classNames.py

I am not clear about what you expect and what you see instead, but the handling of your module works exactly like the math and any other modules: 我不清楚您的期望和看到的内容,但是模块的处理与math和其他模块完全一样:

You just import them. 您只需导入它们。 If this happens for the first time, the file is taken and executed. 如果这是第一次发生,则将提取并执行该文件。 Everything what is left in its namespace after running it is available to you from outside. 运行后保留在其命名空间中的所有内容都可以从外部使用。

If your code only contains just def , class statements and assignments, wou won't notice that anything happens, because, well, nothing "really" happens at this time. 如果您的代码仅包含defclass语句和赋值,那么您将不会注意到有任何事情发生,因为此时没有任何“真正的”事情发生。 But you have the classes, functions and other names available for use. 但是您有可用的类,函数和其他名称。

However, if you have print statements at top level, you'll see that it is indeed executed. 但是,如果您在顶层有print语句,则会看到它确实已执行。

If you have this file anywhere in your Python path (be it explicitly or because it is in the current working directory), you can use it like 如果您在Python路径中的任何位置都有此文件(无论是显式文件还是因为它在当前工作目录中),都可以像

import classNames

and use its contents such as 并使用其内容,例如

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

or you do 或者你做

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

Don't do import classNames.py , as this would try to import module py.py from the package classNames/ . 不要import classNames.py ,因为这会尝试从classNames/包中导入py.py模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM