python中类的一些方法分析

yipeiwu_com5年前Python基础

本文实例分析了python中类的一些方法,分享给大家供大家参考。具体分析如下:

先来看看下面这段代码:

class Super: 
  def delegate(self): 
    self.action() 
     
class Provider(Super): 
  def action(self): 
    print 'in Provider.action' 
     
x = Provider() 
x.delegate() 

本文实例运行环境为Python2.7.6

运行结果如下:

in Provider.action 

在Super类中定义delegate()方法,delegate中调用self.action,在Provider子类中实现action方法。子类调用父类的delegate方法时,实际是调用自己的action方法。。

总之一句话:

这里子类实现了父类delegate中所期望的action方法

再来看看下面这段代码:

class Super: 
  def delegate(self): 
    self.action() 
  def method(self): 
    print 'super method' 
   
class Inherit(Super): 
  pass 
 
class Replace(Super): 
  def method(self): 
    print "replace method" 
     
class Extended(Super): 
  def method(self): 
    print 'in extended class' 
    Super.method(self) 
    print 'out extended class' 
   
class Provider(Super): 
  def action(self): 
    print 'in Provider.action' 
     
x = Inherit() 
x.method() 
print '*'*50 
 
y = Replace() 
y.method() 
print '*'*50 
 
z = Extended() 
z.method() 
print '*'*50 
 
x = Provider() 
x.delegate() 

运行结果如下:

super method 
************************************************** 
replace method 
************************************************** 
in extended class 
super method 
out extended class 
************************************************** 
in Provider.action 

分别继承父类的方法,替换父类的方法,扩展了父类的方法
Super类定义了delegate方法并期待子类实现action函数,Provider子类实现了action方法.

相信本文所述对大家Python程序设计的学习有一定的借鉴价值。

相关文章

Python线程之定位与销毁的实现

Python线程之定位与销毁的实现

背景 开工前我就觉得有什么不太对劲,感觉要背锅。这可不,上班第三天就捅锅了。 我们有个了不起的后台程序,可以动态加载模块,并以线程方式运行,通过这种形式实现插件的功能。而模块更新时候,后...

新年快乐! python实现绚烂的烟花绽放效果

新年快乐! python实现绚烂的烟花绽放效果

做了一个Python的小项目。利用了一点python的可视化技巧,做出烟花绽放的效果,文章的灵感来自网络上一位大神。 一.编译环境 Pycharm 二.模块 1.tkinter:这个...

Django实现文件上传和下载功能

Django实现文件上传和下载功能

本文实例为大家分享了Django下完成文件上传和下载功能的具体代码,供大家参考,具体内容如下 一、文件上传 Views.py def upload(request): if req...

python调用百度语音识别实现大音频文件语音识别功能

本文为大家分享了python实现大音频文件语音识别功能的具体代码,供大家参考,具体内容如下 实现思路:先用ffmpeg将其他非wav格式的音频转换为wav格式,并转换音频的声道(百度支持...

python数据化运营的重要意义

python数据化运营 数据化运营的核心是运营,所有数据工作都是围绕运营工作链条展开的,逐步强化数据对于运营工作的驱动作用。数据化运营的价值体现在对运营的辅助、提升和优化上,甚至某些运营...