如果模块 B 中的方法从模块 A 中获取 class 是否有必要在模块 B 中导入模块 A?

If method in module B takes class from module A is it necessary to import module A in module B?

moduleA.py 包含

class Square:
    def __init__(self, length)
        self.length = length

moduleB.py包含

def scale_shape(shape, scale_factor):
    shape.width = scale_factor*shape.width

moduleA 导入 moduleB 并实现 scale_shape 功能。或者,可能有一个 moduleC,它同时导入 moduleAmoduleB,它实现了 squarescale_shape

我们看到 moduleB.py 中的 function/method 接受类型为 square 的对象,但不需要直接访问 class 因为它没有实例化任何 squares。它仅以某种方式隐式使用 class。

moduleB 中导入 moduleA 是必需的还是最佳做法?

最佳做法是仅导入您需要的内容。

ModuleC 不需要导入 Square 即可使用 scale_shape。更重要的是,scale_shape 不进行类型检查,并且很乐意接受任何具有 width 属性的对象。

如果 scale_shape 仅采用形状对您很重要,请输入检查:

from ModuleA import Square    

def scale_shape(shape, scale_factor):
    assert isinstance(shape, Square)
    shape.width = scale_factor*shape.width