Call of magic methods for python Learning
In python, there are some functions with two underscores (_) on the front and back. Such functions are called in special circumstances, rather than by their names. The following describes several important functions in detail.
The _ init _ function is called automatically when a specific object is created.
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()
When xiang = People () is run in the above function, the _ init _ () function is automatically called, when subclass inherits the _ init _ function of the parent class, it uses Father. in _ init _ (self), self indicates the subclass itself.
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]
The getitem () function is automatically called when [] is used.
Use of iterator functions:
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
The next and _ iter _ functions must be implemented using the built-in iterator.
In addition, there are static functions and variable functions that can be called directly using class names in 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()