Python模擬抽象類上一篇 / 下一篇 2012-04-27 15:10:59 / 個人分類:python Python中沒有abstract關鍵字定義抽象類,但是可以通過NotImplementedError類模擬抽象類 def abstract (): raise NotImplementedError("Abstract") class Person: def __init__ (self): if self.__class__ is Person: abstract() class Student(Person): def __init__ (self): Person.__init__(self) print ("I am student") stu = Student() per = Person() ---------- Python ---------- I am student #這行輸出了 Traceback (most recent call last): File "aa.py", line 19, in <module> per = Person() File "aa.py", line 10, in __init__ abstract() File "aa.py", line 5, in abstract raise NotImplementedError("Abstract") NotImplementedError: Abstract #直接實例化Person類會報錯 輸出完畢 (耗時 0 秒) - 正常終止 |
|