class newDictError(ValueError): """如果向newDict 新增重複值,則引發此異常""" class newDict(dict): """不接受重複值的字典""" def __setitem__(self,key,value): if value in self.values(): if ((key in self and self[key]!=value) or (key not in self)): raise newDictError("這個值已經存在,並對應不同的鍵") super().__setitem__(key,value) demoDict = newDict() demoDict['key']='value' demoDict['other_key']='value2' print(demoDict) demoDict['other_key']='value' print(demoDict)執行結果為:
{'key': 'value', 'other_key': 'value2'}
Traceback (most recent call last):
File "C:UsersmengmaDesktopdemo.py", line 15, in <module>
demoDict['other_key']='value'
File "C:UsersmengmaDesktopdemo.py", line 9, in __setitem__
raise newDictError("這個值已經存在,並對應不同的鍵")
newDictError: 這個值已經存在,並對應不同的鍵
由於目前尚未學習如何處理異常,因此這裡沒有 newDictError 做任何處理,例外處理會在後續章節做詳細講解。
class myList(list): def __init__(self,name): self.name = name def dir(self,nesting = 0): offset = " " * nesting print("%s%s/" % (offset,self.name)) for element in self: if hasattr(element , 'dir'): element.dir(nesting + 1) else: print("%s %s" % (offset,element)) demoList = myList('C語言中文網') demoList.append('http://c.biancheng.net') print(demoList.dir())執行結果如下:
C語言中文網/
http://c.biancheng.net
None