我是否需要导入定义类的模块



我是Python的新手。我正在处理遵循以下结构的代码。

a.py

class A:
    # ...
# some `def`s

b.py

import a
class B:
    # ...
def create_b_from_a(a_obj):
    # reads fields from the instance of A
    # never instantiates an A
    # never uses anything from a.py

import a真的有必要吗?Python 是否需要导入来确定在 A 实例中定义了哪些字段?

仅当您

需要显式引用模块 a 中的某些内容时,才需要import a。如果你永远不需要说a.something,你不应该需要导入。IIUC,您不需要import a,因为您从其他地方获得了A对象,您的代码隐式知道如何处理该类型的对象,并且您不需要模块 a 中的任何新内容。

最新更新