如果模块B中的方法从模块A获得类,是否有必要将模块A导入模块B?

问题描述 投票:0回答:1

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中的函数/方法采用了square类型的对象,但由于它不实例化任何square,因此不需要直接访问该类。它仅以某种方式隐式使用该类。

是否需要或最佳做法是在moduleA中导入moduleB

python python-import
1个回答
0
投票

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

ModuleC不需要导入Square即可使用scale_shape。而且,scale_shape不会进行类型检查,并且会很高兴地使用具有width属性的任何对象。

如果您认为scale_shape仅采用形状很重要,请输入check:

from ModuleA import Square    

def scale_shape(shape, scale_factor):
    assert isinstance(shape, Square)
    shape.width = scale_factor*shape.width
© www.soinside.com 2019 - 2024. All rights reserved.