基本用法:6《学习模块.py :<类class /函数def>》

 

6 《学习模块.py <class /函数def>

模块常用语句 import x(下面红色框内就是test.py模块,import就是在main.py里调用test.py

 

if __name__ == '__main__' 下的程序,指定 Python 模拟环境的程序入口(当前正在运行的.py文件),只在当前运行的.py文件生效,

不支持被导入其他.py文件中。Python 本身并没有规定这么写,这是一种程序员达成共识的编码习惯。

1)举例子

 1 # 1.举例子
 2 ## 文件【main.py】
 3 import test    # 导入test模块
 4 print(test.a)  # 使用test模块-a属性
 5 test.hi()      # 使用test模块-hi方法
 6 
 7 print(test.Go1.a) # 使用test模块-Go1类-a属性
 8 test.Go1.do1()    # 使用test模块-Go1类-do1方法
 9 
10 A = test.Go2()    # 使用test模块-Go1类,进行实例化
11 print(A.a)  # 实例化后,不再需要“模块.”
12 A.do2()     # 实例化后,不再需要“模块.”

## 文件【test.py】
a = '我是模块中的变量a'
def hi():
a = '我是函数里的变量a'
print('函数“hi”已经运行!')
class Go1:
# 如果没有继承的类,class语句中可以省略括号,但定义函数的def语句括号不能省
a = '我是类1中的变量a'
@classmethod
def do1(cls):
print('函数“do1”已经运行!')
class Go2:
a = '我是类2中的变量a'
def do2(self):
print('函数“do2”已经运行!')
print(a) # 打印变量“a”
hi() # 调用函数“hi”

print(Go1.a) # 打印类属性“a”
Go1.do1() # 调用类方法“Go1”

A = Go2() # 实例化“Go2”类
print(A.a) # 打印实例属性“a”
A.do2() # 调用实例方法“do2”

2)【庙里有个老和尚】

 1 # 2. 【庙里有个老和尚】
 2 # 文件【main.py】
 3 import story as s     # 嫌story太长,取个简称s
 4 # import test,story   # 同时导入test模块,story模块
 5 for i in range(10):
 6     print(s.sentence)        # story模块-sentence变量
 7     print(s.Temple.sentence) # story模块-Temple类-sentence属性
 8     s.Temple.reading()       # story模块-Temple类-reading()方法
 9   # s.mountain               # story模块-函数def
10     from story import mountain   # 【模块-函数def】mountain()不用加s.
11     mountain()
12   # from story import *          # 导入模块中任何变量/函数/类方法+属性
13   # from story import a,b,c      # 同时导入story模块-多个函数def
14     A = s.Story()            # 实例化,之后就不用加‘story.’
15     print(A.sentence)
16     A.reading()
17 
18 # 文件【story.py】
19 sentence = '从前有座山,'
20 def mountain():
21     print('山里有座庙,')
22 class Temple:
23     sentence = '庙里有个老和尚,'
24     @classmethod
25     def reading(cls):
26         print('在讲故事,')
27 class Story:
28     sentence = '一个长长的故事。'
29     def reading(self):
30         print('讲的什么故事呢?')

3)【程序入口】,一种共识if __name__==__'main'__

 1 ### 3 【程序入口】,一种共识if __name__==__'main'__
 2 # 文件【main.py】
 3 import story
 4 ## 因为story.py里面有if __name__==__'main'__
 5 ## 它包含的内容只在story.py运行,在main.py不能被用
 6 
 7 # 文件【story.py】
 8 sentence = '从前有座山,'
 9 def mountain():
10     print('山里有座庙,')
11 class Temple:
12     sentence = '庙里有个老和尚,'
13     @classmethod
14     def reading(cls):
15         print('在讲故事,')
16 class Story:
17     sentence = '一个长长的故事。'
18     def reading(self):
19         print('讲的什么故事呢?')
20 ## 下面的内容只能在story.py中运行
21 ## 不能被当做模块导入main.py文件
22 if __name__ == '__main__':
23     print(sentence)
24     mountain()
25     print(Temple.sentence)
26     Temple.reading()
27     A = Story()
28     print(A.sentence)
29     A.reading()
30     print()
原文地址:https://www.cnblogs.com/lj-attitudes0303/p/10354649.html