1、导入整个模块中的函数和变量,代码:
》创建模块say_hello.py文件:
#file:say_hello.py
def say_hi():
print("hello,I'm ISmileLi!")
name = 'ISmileLi'
》使用模块say_hello.py如下:
#file:use_say_hello.py
import say_hello
say_hello.say_hi()
get_name = say_hello.name
print(get_name)
运行结果:

2、导入模块中的某个函数或者变量
#file:use_say_hello_func_attr.py
from say_hello import say_hi,name
say_hi()
print(name)
运行结果同1
3、导入模块中的所有函数和变量
#file:import_say_hello_all
from say_hello import *
say_hi()
print(name)
运行结果同1
4、导入模块时使用as给模块取别名
#file:give_mode_new_name.py
import say_hello as sh
sh.say_hi()
print(sh.name)
运行结果同1
5、导入函数时使用as给函数或者变量取别名
》函数取别名
#file:give_func_new_name.py
from say_hello import say_hi as hi
hi()
运行结果:

》变量取别名
#file:give_func_new_name.py
from say_hello import name as myname
print(myname)
运行结果:

说明:如有错误,欢迎指正。。。
本文介绍了Python中导入模块的多种方式,包括导入整个模块、导入特定函数或变量,以及使用as给模块和函数取别名。通过示例展示了不同导入方法的使用和运行结果。
4963

被折叠的 条评论
为什么被折叠?



