读书笔记:
1、if name == “main“:
用法:
if name == “main”:
–snip–
添加你自己想要的,用于测试模块,演示模块用法等代码。
name:表示模块,类等的名字;
main:模块,xxx.py文件本身;
被直接执行时,对应的模块名就是main了
作为模块,被别的Python程序导入(import)时,模块名就是本身文件名xxx了。
演示如下:
# -*- coding: gbk -*-
def test():
print("it's a test!")
#运行此模块时,__name__ 就等于 __main__
print("\n__name__ 返回 : %s\n"% __name__)
#此模块被导入时, 用test.__name__方法获取文件名,就等于实际的名字,即test
print("\ntest.__name__返回 : %s\n"%test.__name__)
if __name__ == "__main__":
test()
2、导入模块和导入类
补充:
如果定义一个类B,可以直接给例对象b设置属性和值,b.x = 1 ,通过b.(双下划线)dict(双下划线)魔法方法可以查到:
>>> class B:
def f():
print("HomesomeTree")
>>> b = B()
>>> b.x = 1
>>> b.__dict__
{'x': 1}
>>>
>>> class Const:
def __setattr__(self,name,value):
if name in self.__dict__:
raise TypeError("常量不可修改!")
if not name.isupper():
raise TypeError("常量名必须由大写字母组成!")
self.__dict__[name] = value
>>> a = Const()
>>> a.x = 100
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
a.x = 100
File "<pyshell#23>", line 7, in __setattr__
raise TypeError("常量名必须由大写字母组成!")
TypeError: 常量名必须由大写字母组成!
>>> a.N = 11111
>>> a.N = 1
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
a.N = 1
File "<pyshell#23>", line 4, in __setattr__
raise TypeError("常量不可修改!")
TypeError: 常量不可修改!
>>> Const.Num = 10000
>>> Const.Num = 1
>>> Const.N = 999
>>> Const.N = 1
>>> Const.__dict__
mappingproxy({'__module__': '__main__', '__setattr__': <function Const.__setattr__ at 0x0000000002FC8C80>, '__dict__': <attribute '__dict__' of 'Const' objects>, '__weakref__': <attribute '__weakref__' of 'Const' objects>, '__doc__': None, 'Num': 1, 'N': 1})