python复习100天

python复习第7天:模块和包

2020-03-20  本文已影响0人  潮办公

title: python复习100天--第7天
date: 2020-03-13 14:00:24
tags:
- python
- 基础
categories: python复习
top: 8


模块和包

模块

# 第一步,自己动手写一个模块
def fun1():
    """
    随便写一个函数,用来打印"hello world"
    :return: None
    """
    print('hello world')
# 写完后重命名为test.py文件
# 调用模块
import test


test.fun1()  # 调用模块的函数
"""
# 输出结果
hello world
"""
from test import fun1


fun1()

"""
# 输出结果
hello world
"""
from test import *


fun1()

"""
# 输出结果
hello world
"""
from test import fun1 as f1
import test as t

f1()
t.fun1()
"""
# 输出结果
hello world
hello world
"""

name属性

# 第一步,自己动手写一个模块
def fun1():
    """
    随便写一个函数,用来打印"hello world"
    :return: None
    """
    print('hello world')


if __name__ == '__main__':

    def fun2():
        print('这个函数只能test模块使用')
    fun1()
    fun2()

# 写完后重命名为test.py文件
"""
# 运行test模块后的结果
hello world
这个函数只能test模块使用
"""
from test import *

fun1()
fun2()

"""
hello world
Traceback (most recent call last):
  File "/home/tlntin/PycharmProjects/study/002.py", line 4, in <module>
    fun2()
NameError: name 'fun2' is not defined
"""
# 在其它模块导入test模块后,运行fun2函数失败,提示该函数未定义
# main函数下的代码只能在该模块运行,不能被导入运行
import test
print(dir(test))

"""
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'fun1']
"""

标准模块

from os.path import exists

print(exists('test.py'))  # 验证文件路径是否存在

"""
# 输出结果
True
"""
上一篇 下一篇

猜你喜欢

热点阅读