[英]Python: importing another .py file
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. 但是当我试着打电话时,它说无法找到def。 I also tried:
我也尝试过:
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. 它只是给了我一个错误。
import file2
loads the module file2
and binds it to the name file2
in the current namespace. 加载模块
file2
并将其绑定到当前名称空间中的名称file2
。 b
from file2
is available as file2.b
, not b
, so it isn't recognized as a method. 来自
file2
b
可用作file2.b
,而不是b
,因此它不被识别为方法。 You could fix it with 你可以修复它
from file2 import b
which would load the module and assign the b
function from that module to the name b
. 这将加载模块并将该模块的
b
函数分配给名称b
。 I wouldn't recommend it, though. 不过我不推荐它。 Import
file2
at 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. 在顶层导入
file2
并定义一个委托给file2.b
的方法,或者如果经常需要在不相关的类中使用相同的方法,则定义可以继承的mixin超类。 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. 导入一个函数以将其用作方法会让人感到困惑,如果您尝试使用的函数在C中实现,它就会中断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.