分享

Python模拟抽象类

 我的菜谱123 2013-01-25

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 秒) - 正常终止

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约