python學習之魔法方法的呼叫

2021-06-29 00:17:43 字數 1836 閱讀 8035

在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()

Python魔法方法 基本的魔法方法

new cls 1.new 是在乙個物件例項化時候所呼叫的第乙個方法 2.他的第乙個引數是這個類,其他的引數是用來直接傳遞給 init 方法 3.new 決定是否使用該 init 方法,因為.new 可以直接呼叫其他類的構造方法,或者返回別的例項物件來作為本類的例項,如果 new 沒有返回例項物件,...

python的魔法 Python 魔法方法

先給個例子 class frenchdeck ranks str n for n in range 2,11 list jqka suits spades diamonds clubs hearts split def init self self.cards card rank,suit for ...

Python 基礎之魔法方法

構造方法類似於初始化方法,但是構造方法與其他普通的方法的不同之處在於,當乙個物件被建立之後,會立即呼叫構造方法。class servant object definit self self.servant saber fb servant fb.init print fb.servant class...