python——模块

先写两个测试模块test1.py和test2.py以备调用
test1.py

# _*_ coding:utf-8 _*_
"""
file:test1.py
date:2018-07-24 11:14 AM
author:wwy
desc:

"""


title = '模块1'
# 函数
def say_hello():
    print '我是 %s' % title

# 类
class Cat(object):
    pass

test2.py

# _*_ coding:utf-8 _*_
"""
file:test2.py
date:2018-07-24 11:14 AM
author:wwy
desc:

"""


title = '模块2'
# 函数
def say_hello():
    print '我是 %s' % title

# 类
class Dog(object):
    pass

模块——03.py

# _*_ coding:utf-8 _*_
"""
file:模块——03.py
date:2018-07-24 11:09 AM
author:wwy
desc:

"""


#在导入模块时,每个导入应独占一行
import test1
import test2

test1.say_hello()
test2.say_hello()

dog =test2.Dog()
print dog

cat = test1.Cat()
print cat

运行结果:
这里写图片描述
模块——04.py

# _*_ coding:utf-8 _*_
"""
file:模块——04.py
date:2018-07-24 11:09 AM
author:wwy
desc:

"""


# 使用as指定模块的别名(大驼峰命名法)
import test1 as CatModule
import test2 as DogModule

DogModule.say_hello()
CatModule.say_hello()

dog = DogModule.Dog()
print dog
cat = CatModule.Cat()
print cat

这里写图片描述
模块——05.py

# _*_ coding:utf-8 _*_
"""
file:模块——05.py
date:2018-07-24 11:39 AM
author:wwy
desc:

"""


from test1 import Cat
from test2 import say_hello
from test1 import say_hello        # test1将test2覆盖了,所以运行后只显示模块1

say_hello()
fendai = Cat()

运行结果:
这里写图片描述
模块——06.py

# _*_ coding:utf-8 _*_
"""
file:模块——06.py
date:2018-07-24 11:50 AM
author:wwy
desc:

"""


from test1 import Cat
from test2 import say_hello
from test1 import say_hello as test1_say_hello

say_hello()
test1_say_hello()
fendai = Cat()

运行结果:
这里写图片描述

# _*_ coding:utf-8 _*_
"""
file:模块——07.py
date:2018-07-24 11:52 AM
author:wwy
desc:
python的解释器在导入模块的时候,会:
    1.搜索当前目录指定的模块文件,如果有就直接导入
    2.如果没有,再搜索系统目录
注意:在开发时,给文件起名,不要和系统模块文件重名
"""
#取一个随机整数

import random
rand = random.randint(0,10)
print rand

运行结果:
这里写图片描述

__name__属性

# _*_ coding:utf-8 _*_
"""
file:test.py
date:2018-07-24 11:43 AM
author:wwy
desc:
__name__属性
__name__属性可以做到,测试模块的代码只在测试的情况下被运行,而在被导入时不执行
__name__是python的一个内置属性,记录着一个字符串
如果是被其他文件导入时,__name__就是模块名
如果是当前执行的程序,__name__就是__main__

"""

# 全局变量,函数,类 直接执行的代码不是向外界提供的工具
def say_hello():
    print 'hello'

#print 'have a nice day!!'
# 如果直接在模块中输入,得到的是__main__
if __name__ == '__main__':
    print __name__
    print 'zmy开发的程序'
    say_hello()

运行结果:
这里写图片描述

# _*_ coding:utf-8 _*_
"""
file:模块——08.py
date:2018-07-24 1:56 PM
author:wwy
desc:
在很多python文件中会看到以下格式的代码

    # 导入模块
    # 定义全部变量
    # 定义类
    # 定义函数

    # 在代码下方

    def main()
        pass

    if __name__ == '__main__'
        main()
"""
# 在导入的.py文件中,输出的是 文件名

import test

这里写图片描述
__name__属性可以做到,测试模块的代码只在测试的情况下被运行,而在被导入时不执行
在模块——08.py中并没有调用test.py

猜你喜欢

转载自blog.csdn.net/wwy0324/article/details/81259470
今日推荐