在python中存在一些前面和后边都加上两个下划线的函数,这种函数会在一些特殊的情况下被调用,而不是根据他们的名字被调用。下面详细介绍几个重要的函数.
__init__函数,,这类进行初始化的函数,在创建一个具体的对象的时候会自动的调用。
class People:def __init__(self):self.university="shandong"def getUniversity(self):return self.universityxiang=People() #when you create an object, the __init__ method will be excuted dynamicallyprint xiang.getUniversity() class student(People):def __init__(self):People.__init__(self)name="xiang"gao=student()print gao.getUniversity()
上述函数中在运行xiang=People()的时候会自动调用__init__()函数,而子类继承父类的__init__函数的时候使用的是Father.__init__(self)其中self表示子类自身。
class counterList(list):def __init__(self,*args):self.counter=0list.__init__(self,*args)def __getitem__(self,index): #it will be exceted dynamically when you use []self.counter+=1print "I am running"return list.__getitem__(self,index)count=counterList(range(0,10))print count.counterprint count[0]+count[1]getitem()函数在使用[ ]时自动调用。
迭代器函数的使用:
class Fibs:def __init__(self):self.a=0self.b=1def next(self):self.a,self.b=self.b,self.a+self.breturn self.adef __iter__(self):return selffibs=Fibs()for f in fibs:if f>5:print f break使用其自带的迭代器必须实现next和__iter__函数。
此外python中还存在可以直接使用类名调用的函数静态函数和类变量函数
class MyClass:@staticmethod #create static methoddef smath():print "this is static method"@classmethod#create class methoddef cmath(clf):print "this is class method"MyClass.smath()MyClass.cmath()
只要有信心,人永远不会挫败