说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
导入了moduleA
和moduleB
,它们同时实现了square
和scale_shape
。
我们看到moduleB.py
中的函数/方法采用了square
类型的对象,但由于它不实例化任何square
,因此不需要直接访问该类。它仅以某种方式隐式使用该类。
是否需要或最佳做法是在moduleA
中导入moduleB
?
最佳做法是仅导入您需要的内容。
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