Python __import__() 函数
当我们编写Python程序时,我们需要各种其他模块来在我们当前的程序中利用它们的功能、类等。我们可以在运行时使用import函数导入这些模块。虽然您也可以在代码的开头导入命名模块,但您可能只需要在几行代码中临时使用该模块,或者您想从模块中复制一个对象并修改和使用它。
语法
该__import__()函数的语法是-
__import__(name, globals=None, locals=None, fromlist=(), level=0) Where name - the name of the module you want to import globals and locals - determines how to interpret name fromlist - objects or submodules that should be imported by name level - specifies whether to use absolute or relative imports
在下面的示例中,我们导入DateTime模块并根据程序中的需要使用值创建自定义对象。
示例
dttime = __import__('datetime', globals(), locals(), [], 0)
print(dttime.datetime.now())
#复制dttime
x = dttime.datetime.now()
#获取您的自定义结果
print(x.strftime("%d-%B"))输出结果运行上面的代码给我们以下结果-
2021-01-12 07:38:54.903330 12-January
不鼓励使用__import__,您可以在代码的开头导入整个模块以提高效率。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下