__init__.py 文件用法

__init__.py 文件用法

  • 简介
  • __init__.py用法1
  • __init__.py用法2

简介

__init__.py文件的作用是把整个文件夹当作一个python模块包来处理,密度是科学地管理命名空间。当运行代码import d2l时,会执行文件夹d2l下的_init_.py文件。如图所示
__init__.py 文件用法_第1张图片
如果要导入该文件夹下的Python函数。

init.py用法1

目录结构如下

--base_dir
    |--d2l
        ||--torch.py
            def func1()
            def func2()
    |--main.py

module2.py要导入./d2l/torch.py中的文件,需要在d2l目录下添加一个__init__.py文件,这样python才会把该文件夹当成一个模块(module)来处理,然后在main.py中加入如下代码:

from d2l.torch import *
#或者
import d2l.torch as tch

即可导入该python文件中的内容。

init.py用法2

我们还可以把d2l目录下torch模块的函数直接汇集到d2l模块下使用,例如
文件目录如下:

--base_dir
    |--d2l
    	||--__init__.py
        ||--torch.py
            def hello()
    |--module2.py

torch.py的内容如下:

def hello():
	print("hello there")
	return 

我们在main.py中想通过如下代码调用hello()函数:

import d2l
d2l.hello()

那么应该在__init__.py 中写入:

#__init__.py
from .d2l.torch import hello 

也可以通过from .d2l.torch import *一次性导入所有函数。

你可能感兴趣的:(python,pytorch,pycharm)