python學習之魔法方法的調用

在python中存在一些前面和後邊都加上兩個下劃線的函數,這種函數會在一些特殊的情況下被調用,而不是根據他們的名字被調用。下面詳細介紹幾個重要的函數.

__init__函數,這類進行初始化的函數,在創建一個具體的對象的時候會自動的調用。

class People:
	def __init__(self):
		self.university="shandong"
	def getUniversity(self):
		return self.university
xiang=People() #when you create an object, the __init__ method will be excuted dynamically
print 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=0
		list.__init__(self,*args)
	def __getitem__(self,index): #it will be exceted dynamically when you use []
		self.counter+=1
		print "I am running"
		return list.__getitem__(self,index)
count=counterList(range(0,10))
print count.counter
print count[0]+count[1]
getitem()函數在使用[ ]時自動調用。

迭代器函數的使用:

class Fibs:
	def __init__(self):
		self.a=0
		self.b=1
	def next(self):
		self.a,self.b=self.b,self.a+self.b
		return self.a
	def __iter__(self):
		return self
fibs=Fibs()
for f in fibs:
	if f>5:
		print f 
		break
使用其自帶的迭代器必須實現next和__iter__函數。

此外python中還存在可以直接使用類名調用的函數靜態函數和類變量函數

class MyClass:
	@staticmethod  #create static method
	def smath():
		print "this is static method"
	@classmethod	#create class method
	def cmath(clf):
		print "this is class method"
MyClass.smath()
MyClass.cmath()






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章