In python, what is the difference between #39;import foo.bar as bar#39; and #39;from foo import bar#39;?(在Python中,将foo.bar作为bar导入与从foo导入bar导入有什么不同?)
问题描述
我在pyTorch和matplotlib中看到此约定:
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
是否有理由将整个路径(module.submodule
)作为别名导入,而不仅仅是子模块?如果我这样导入,有什么不同:
from torch import nn
from torch import optim
from matplotlib import pyplot as plt
编辑:对于一般情况:
import foo.bar as bar # [1]
from foo import bar # [2]
是否存在引用bar
的代码,以便它将与[1]
一起运行,而不是[2]
(反之亦然)?即这两种导入方式是否功能不同?
推荐答案
在幕后,所有导入语句实质上都映射到内置__import__
,例如:
import torch.nn as nn
变为
nn = __import__("torch.nn", globals(), locals(), [], 0)
类似:
from torch import nn
变为
nn = __import__("torch", globals(), locals(), ["nn"], 0)
略有不同,但功能相同。
引用:https://docs.python.org/3/library/functions.html#import
这篇关于在Python中,将foo.bar作为bar导入与从foo导入bar导入有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!