Python:导入另一个 .py 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17977564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:39:13  来源:igfitidea点击:

Python: importing another .py file

pythonimportfunction

提问by user2638731

I have a class and I want to import a def function by doing:

我有一个类,我想通过执行以下操作导入一个 def 函数:

import <file>

but when I try to call it, it says that the def can not be found. I also tried:

但是当我尝试调用它时,它说找不到 def。我也试过:

from <file> import <def>

but then it says global name 'x' is not defined.

但随后它说未定义全局名称“x”。

So how can I do this?

那么我该怎么做呢?

Edit:

编辑:

Here is a example of what I am trying to do. In file1.py I have:

这是我正在尝试做的一个例子。在 file1.py 我有:

var = "hi"

class a:
  def __init__(self):
    self.b()

  import file2

a()

and in file2.py I have:

在 file2.py 我有:

def b(self):
  print(var)

it is just giving me a error though.

它只是给我一个错误。

回答by user2357112 supports Monica

import file2

loads the module file2and binds it to the name file2in the current namespace. bfrom file2is available as file2.b, not b, so it isn't recognized as a method. You could fix it with

加载模块file2并将其绑定到file2当前命名空间中的名称。bfromfile2是可用的file2.b,不是可用的b,所以它不被识别为一种方法。你可以用

from file2 import b

which would load the module and assign the bfunction from that module to the name b. I wouldn't recommend it, though. Import file2at top level and define a method that delegates to file2.b, or define a mixin superclass you can inherit from if you frequently need to use the same methods in unrelated classes. Importing a function to use it as a method is confusing, and it breaks if the function you're trying to use is implemented in C.

这将加载模块并将该模块中的b函数分配给name b。不过,我不会推荐它。file2在顶层导入并定义一个委托给 的方法file2.b,或者定义一个 mixin 超类,如果您经常需要在不相关的类中使用相同的方法,您可以从中继承。导入一个函数以将其用作方法是令人困惑的,如果您尝试使用的函数是用 C 实现的,它就会中断。