(1)self参数用于类定义中,不可省略,独立的函数或方法中不含有self参数。self不是Python的关键字,可替换成别的。在类实例化时,self自动绑定到self实例上,指向类实例对象本身,已完成类对自身属性的调用。
>>> class Person:
def __init__(self,name,age):
self.name = name
self.age = age
>>> p = Person('jack',19)
>>> p.name
'jack'
>>> p.age
19
(2)__doc__ 是函数属性,双下划线表示其为特殊属性,会在特殊情况下被Python调用,用以添加解释文档。
>>> def add(a,b):
'add a and b,caculate their sum'
print a+b
>>> add.__doc__
'add a and b,caculate their sum'
(3)__init__ 是构造函数,当一个对象被创建后,会立即调用构造函数,而不用再实例化后调用其中方法。构造函数的参数可选,但至少包含一个self。当输入self以外的参数时,会作为默认参数使用。
>>> class Ft:
def init(self):
self.somevar = 42
>>> ft = Ft()
>>> ft.somevar
Traceback (most recent call last):
File "<pyshell#54>", line 1, in <module>
ft.somevar
AttributeError: Ft instance has no attribute 'somevar'
>>> ft.init()
>>> ft.somevar
42
>>> class FtBar:
def __init__(self):
self.somevar = 42
>>> ftb = FtBar()
>>> ftb.somevar
42
(4)__name__ 变量用于检查程序入口。模块用于定义函数、类和其他的一些内容,但是在首次导入模块时,模块会执行其中的函数,为了保证模块在导入时仅仅是以模块名显示,在调用时才会执行,可以在程序中“告知”模块是作为程序执行还是被导入到其他程序,因此,需要使用__name__ 变量。在“主程序”中,变量__name__ 的值是__main__ 。
def hello():
print 'hello world'
def test():
hello()
if __name__ == '__main__':
test()
运行结果:
>>> import name_test
>>> name_test.hello()
hello world
参考文献:Python基础教程[第2版]