导入的 类 可以使用导入文件中的函数和 类 吗?
Can imported classes use functions and classes from the importing file?
我想稍微整理一下我的代码,因此决定将主文件分成多个较小的文件。
这是旧设置
coefficient = 2
def foo(x):
return coefficient*x
class Pair:
def __init__(self,x,y):
self.x = x
self.y = y
class Bar:
def __init__(self,value):
self.x = value
self.y = foo(value)
self.point = Pair(self.x, self.y)
如果我只将 Bar
移动到 file.py
,使用 from .file import *
从那里导入它并尝试在代码中的任何地方使用它,我会收到 name is not defined
错误对于 file
中缺少的任何内容,除非我也将 coefficient
、foo
和 Pair
移到那里。由此我认为,如果我将 foo
或 Pair
移动到第三个文件并从那里导入,它尤其不会起作用,我也打算这样做。
我是不是遗漏了什么,或者这实际上不可能做到?
通常情况下,您应该能够从另一个文件中调用函数。但是,如果导入的 class 中的函数基于它要查找的文件,我认为你不能调用它们
'foo' 和 'Pair' 在 bar 的文件中。
希望这是有道理的。
我想稍微整理一下我的代码,因此决定将主文件分成多个较小的文件。
这是旧设置
coefficient = 2
def foo(x):
return coefficient*x
class Pair:
def __init__(self,x,y):
self.x = x
self.y = y
class Bar:
def __init__(self,value):
self.x = value
self.y = foo(value)
self.point = Pair(self.x, self.y)
如果我只将 Bar
移动到 file.py
,使用 from .file import *
从那里导入它并尝试在代码中的任何地方使用它,我会收到 name is not defined
错误对于 file
中缺少的任何内容,除非我也将 coefficient
、foo
和 Pair
移到那里。由此我认为,如果我将 foo
或 Pair
移动到第三个文件并从那里导入,它尤其不会起作用,我也打算这样做。
我是不是遗漏了什么,或者这实际上不可能做到?
通常情况下,您应该能够从另一个文件中调用函数。但是,如果导入的 class 中的函数基于它要查找的文件,我认为你不能调用它们 'foo' 和 'Pair' 在 bar 的文件中。
希望这是有道理的。