python中类的一些方法分析
本文实例分析了python中类的一些方法,分享给大家供大家参考。具体分析如下:
先来看看下面这段代码:
classSuper: defdelegate(self): self.action() classProvider(Super): defaction(self): print'inProvider.action' x=Provider() x.delegate()
本文实例运行环境为Python2.7.6
运行结果如下:
inProvider.action
在Super类中定义delegate()方法,delegate中调用self.action,在Provider子类中实现action方法。子类调用父类的delegate方法时,实际是调用自己的action方法。。
总之一句话:
这里子类实现了父类delegate中所期望的action方法
再来看看下面这段代码:
classSuper: defdelegate(self): self.action() defmethod(self): print'supermethod' classInherit(Super): pass classReplace(Super): defmethod(self): print"replacemethod" classExtended(Super): defmethod(self): print'inextendedclass' Super.method(self) print'outextendedclass' classProvider(Super): defaction(self): print'inProvider.action' x=Inherit() x.method() print'*'*50 y=Replace() y.method() print'*'*50 z=Extended() z.method() print'*'*50 x=Provider() x.delegate()
运行结果如下:
supermethod ************************************************** replacemethod ************************************************** inextendedclass supermethod outextendedclass ************************************************** inProvider.action
分别继承父类的方法,替换父类的方法,扩展了父类的方法
Super类定义了delegate方法并期待子类实现action函数,Provider子类实现了action方法.
相信本文所述对大家Python程序设计的学习有一定的借鉴价值。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短