python:__name__='__main__'和__init__的作用
本文参考:编程青年的崛起 https://www.cnblogs.com/alan-babyblog/p/5147770.html
菜鸟教程Python3 http://www.runoob.com/python3/python3-stdlib.html
__name__='__main__'
"make a script both importable and executable"
写的脚本既可以导入别的模块使用,,也可以自己执行,
在本文件中运行__name__ 的值为"__main__"
在别的模块中__name__为python文件的名字
#module.py
def main():
print "we are in %s"%__name__
if __name__ == '__main__':
main()
运行module.py 结果为:we are in __main__ if的结果为true
#anothermodle.py
from module import main
main()
运行anothermodle 结果为we are in module if的结果为false
init
__init__()是类的构造方法
类定义了 __init__() 方法的话,类的实例化操作会自动调用 __init__() 方法
#!/usr/bin/python3
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print(x.r, x.i) # 输出结果:3.0 -4.5
self代表类的实例,而非类
类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称, 按照惯例它的名称是 self。
class Test:
def prt(self):
print(self)
print(self.__class__)
t = Test()
t.prt()