代码之家  ›  专栏  ›  技术社区  ›  kgui K-K

python导入差异

  •  0
  • kgui K-K  · 技术社区  · 7 年前

    在python中,它看起来像自定义类,在导入时需要完全分类

    例如,

    from analytics.npv_differences import NpvDifferences
    

    分析
    ---npv_differences.py(包含npvddifferences类)

    当下列操作不起作用时:

    from analytics import NpvDifferences
    

    然而,对于熊猫来说,以下两项工作

    from pandas import DataFrame
    from pandas.core.frame import DataFrame
    

    为什么不同?

    1 回复  |  直到 7 年前
        1
  •  1
  •   illright Dexterxiee    7 年前

    有什么区别?

    区别在于 __init__.py 文件。

    它是一个将包含python代码的目录转换为python的文件 包裹 . 这是 documenation 在包裹上。

    这个 _初始年 包含导入包时运行的代码。
    其中包括:

    • import module
    • import module.submodule
    • from module import something
    • from module.submodule import something

    在所有这些情况下 module/__init__.py 被处决。您可以通过添加 print() 在文件内部调用并在导入期间观察输出。

    它可以是空的,但大多数情况下,它是从子目录导入的,以允许使用简短的导入表单。上面说 __init__.py 文件来源 pandas 来源。如果您快速查看,您将看到有来自子包的导入。

    怎么做呢?

    如果您创建 _初始年 目录中的文件 analytics 在那里导入类,就可以使用 熊猫 .

    你的 analytics/__init__.py 文件应该包含如下内容:

    from analytics.npv_differences import NpvDifferences
    

    这个 分析 可以省略部分导入,将其转换为 相对进口 . 如果你把这个放进去 _初始年 ,您将得到相同的结果:

    from .npv_differences import NpvDifferences
    

    相对导入更好,因为如果您碰巧将包重命名为其他包,则导入不会中断。

    为什么这样做?

    为什么要在内部导入 _初始年 允许短期进口是因为 中定义的任何变量 _初始年 在模块级可用 .

    例如,如果 模块/初始化 包含以下代码:

    from .submodule import SomeClass  # this defines a `SomeClass` variable
    __doc__ = '''This behaviour is commonly used to define 
                 module-level documentation, available with 
                 a call `help(module)`.'''
    config_var = 1337
    

    然后,以下情况成为可能:

    import module
    help(module)  # will output the content of the __doc__ variable
    module.SomeClass()  # create an instance of module.submodule.SomeClass
    print(module.config_var)  # prints 1337
    

    这就是为什么在 熊猫 _初始年 任何不必要的变量都会用 del . 请确保不要污染模块级命名空间。

    推荐文章