Python 類可以定義專用方法,專用方法是在特殊情況下或當使用特別語法時由 Python 替你調用的,而不是在代碼中直接調用(象普通的方法那樣)。
.1 __init__
類似于構造函數
#!/usr/local/bin/python
class Study:
def __init__(self,name=None):
self.name = name
def say(self):
print self.name
study = Study("Badboy")
study.say()
.2 __del__
類似于析構函數
#!/usr/local/bin/python
class Study:
def __init__(self,name=None):
self.name = name
def __del__(self):
print "Iamaway,baby!"
def say(self):
print self.name
study = Study("zhuzhengjun")
study.say()
.3__repr__
使用repr(obj)的時候,會自動調用__repr__函數,該函數返回對象字符串表達式,
用于重建對象,如果eval(repr(obj))會得到1個對象的拷貝。
#!/usr/local/bin/python
class Study:
def __init__(self,name=None):
self.name = name
def __del__(self):
print "Iamaway,baby!"
def say(self):
print self.name
def __repr__(self):
return "Study('jacky')"
study = Study("zhuzhengjun")
study.say()
print type(repr(Study("zhuzhengjun"))) # str
print type(eval(repr(Study("zhuzhengjun")))) # instance
study = eval(repr(Study("zhuzhengjun")))
study.say()
.4__str__
Python能用print語句輸出內建數據類型。有時,程序員希望定義1個類,要求它的對象也能用print語句輸出。Python類可定義特殊方法__str__,為類的對象提供1個不正式的字符串表示。如果類的客戶程序包括以下語句:
print objectOfClass
那末Python會調用對象的__str__方法,并輸出那個方法所返回的字符串。
#!/usr/local/bin/python
class PhoneNumber:
def __init__(self,number):
self.areaCode=number[1:4]
self.exchange=number[6:9]
self.line=number[10:14]
def __str__(self):
return "(%s) %s-%s"%(self.areaCode,self.exchange,self.line)
def test():
newNumber=raw_input("Enter phone number in the form. (123) 456⑺890:
")
phone=PhoneNumber(newNumber)
print "The phone number is:"
print phone
if__name__=="__main__":
test()
方法__init__接收1個形如"(xxx) xxx-xxxx"的字符串。字符串中的每一個x都是電話號碼的1個位數。方法對字符串進行分解,并將電話號碼的不同部份作為屬性存儲。
方法__str__是1個特殊方法,它構造并返回PhoneNumber類的1個對象的字符串表示。解析器1旦遇到以下語句:
print phone
就會履行以下語句:
print phone.__str__()
程序如果將PhoneNumber對象傳給內建函數str(如str(phone)),或為PhoneNumber對象使用字符串格式化運算符%(例如"%s"%phone),Python也會調用__str__方法。
.5__cmp __
比較運算符,0:等于 1:大于 ⑴:小于
class Study:
def __cmp__(self, other):
if other > 0 :
return 1
elif other < 0:
return - 1
else:
return 0
study = Study()
if study > ⑴0:print 'ok1'
if study < ⑴0:print 'ok2'
if study == 0:print 'ok3'
打印:ok2 ok3
說明:在對類進行比較時,python自動調用__cmp__方法,如⑴0 < 0 返回 ⑴,也就是說study 應當小與 ⑴0,估打印ok2
.6__getitem__
__getitem__ 專用方法很簡單。象普通的方法 clear,keys 和 values 1樣,它只是重定向到字典,返回字典的值。
class Zoo:
def __getitem__(self, key):
if key == 'dog':return 'dog'
elif key == 'pig':return 'pig'
elif key == 'wolf':return 'wolf'
else:return 'unknown'
zoo = Zoo()
print zoo['dog']
print zoo['pig']
print zoo['wolf']
打印 dog pig wolf
.7__setitem__
__setitem__ 簡單地重定向到真實的字典 self.data ,讓它來進行工作。
class Zoo:
def __setitem__(self, key, value):
print 'key=%s,value=%s' % (key, value)
zoo = Zoo()
zoo['a'] = 'a'
zoo['b'] = 'b'
zoo['c'] = 'c'
打印:
key=a,value=a
key=b,value=b
key=c,value=c
.8 __delitem__
__delitem__ 在調用 del instance[key] 時調用 ,你可能記得它作為從字典中刪除單個元素的方法。當你在類實例中使用 del 時,Python 替你調用 __delitem__ 專用方法。
class A:
def __delitem__(self, key):
print 'delete item:%s' %key
a = A()
del a['key']
Method | Overloads | Call for |
---|---|---|
init | 構造函數 | X=Class() |
del | 析構函數 | 對象燒毀 |
repr | 打印轉換 | print X,repr(X) |
str | 打印轉換 | print X,str(X) |
call | 調用函數 | X() |
getattr | 限制 | X.undefine |
setattr | 取值 | X.any=value |
getitem | 索引 | X[key],For If |
setitem | 索引 | X[key]=value |
len | 長度 | len(X) |
iter | 迭代 |
For In |
add | + | X+Y,X+=Y |
sub | - | X-Y,X-=Y |
mul | XY | |
radd | 右加+ | +X |
iadd | += | X+=Y |
or | | | X|Y,X|=Y |
cmp | 比較 == | X==Y,X |
lt | 小于< | X |
eq | 等于= | X=Y |
class Number(object): def __init__(self, value): self.value = value # 加重載 def __add__(self, other): return Number(self.value + other.value) # 打印重載 def __str__(self): return 'The value is %d.' % self.value # 比較重載 def __cmp__(self, other): return cmp(self.value, other.value) >>> x = Number(1) >>> y = Number(2) >>> print x + y The value is 3. >>> x > y False >>> x < y True
參考文獻:
http://5ydycm.blog.51cto.com/115934/157548
http://wuyuans.com/2013/05/python-class/
上一篇 莫比烏斯反演