欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python 模拟抽象类

发布时间:2025/7/14 python 53 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python 模拟抽象类 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

2019独角兽企业重金招聘Python工程师标准>>>

继承是面向对象的重要特征之一,继承是两个类或者多个类之间的父子关系,子进程继承了父进程的所有公有实例变量和方法。继承实现了代码的重用。重用已经存在的数据和行为,减少代码的重新编写,python在类名后用一对圆括号表示继承关系, 括号中的类表示父类,如果父类定义了__init__方法,则子类必须显示地调用父类的__init__方法,如果子类需要扩展父类的行为,可以添加__init__方法的参数。

下面演示继承的实现

class Fruit:def __init__(self, color):self.color = colorprint "fruit's color: %s" %self.colordef grow(self):print "grow..."class Apple(Fruit):                               #继承了父类def __init__(self, color):                  #显示调用父类的__init__方法Fruit.__init__(self, color)print "apple's color: %s" % self.colorclass Banana(Fruit):                              #继承了父类def __init__(self, color):                  #显示调用父类的__init__方法Fruit.__init__(self, color)print "banana's color:%s" %s self.colordef grow(self):                             #覆盖了父类的grow方法print "banana grow..."if __name__ == "__main__": apple = Apple("red") apple.grow() banana = Banana("yellow") banana.grow() 输出结果:fruit‘s color : redapple's color : redgrow...fruit's color : yellowbanana's color : yellowbanana grow...


抽象类的模拟

     抽象类是对一类事物特征和行为的抽象,抽象类由抽象方法组成,python2.5没有提供抽象类的语法,抽象类的特征是不能被实例化,但是可以通过python的NotImplementedError类来模拟抽象类,NotImplementedError类继承自python运行时错误类RuntimeError。当对抽象类进行实例化时,将抛出异常。

模拟抽象类的实现 def abstract():                                 #定义了全局函数raise NotImplimentedError(“abstract”):class Fruit:def __init__(self):if self.__class__ is Fruit:            #如果实例化的类是Fruit,则抛出异常abstract()print "Fruit..."class Apple(Fruit):def __init__(self):Fruit.__init__(self)print "Apple..."if __name__ == "__main__": apple = Apple()                                   #输出: Fruit   Apple


同样python也没有提供对接口的支持。接口是特殊的抽象类,接口没有数据成员,而是一组未实现的方法的集合。


转载于:https://my.oschina.net/lcxidian/blog/396422

总结

以上是生活随笔为你收集整理的python 模拟抽象类的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。