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使用matplotlib实现绘制自定义图形功能示例

Python使用matplotlib实现绘制自定义图形功能示例

本文实例讲述了Python使用matplotlib实现绘制自定义图形功能。分享给大家供大家参考,具体如下: 一 代码 from matplotlib.path importPath...

Python3.5基础之NumPy模块的使用图文与实例详解

Python3.5基础之NumPy模块的使用图文与实例详解

本文实例讲述了Python3.5基础之NumPy模块的使用。分享给大家供大家参考,具体如下: 1、简介 2、多维数组——ndarray...

Python实现随机取一个矩阵数组的某几行

废话不多说了,直接上代码吧! import numpy as np array = np.array([0, 0]) for i in range(10): array =...

Python 网页解析HTMLParse的实例详解

Python 网页解析HTMLParse的实例详解 使用python将网页抓取下来之后,下一步我们就应该解析网页,提取我们所需要的内容了,在python里提供了一个简单的解析模块HTML...

Python和perl实现批量对目录下电子书文件重命名的代码分享

经常会遇到下载的文件或电子书,名字中间都包含了一些网址信息,实际使用中由于名字太长不方便,下面的脚本使用正则表达式来对目录下的所有文件重命名: 例如: 修改前:[【听图阁-专注于Pyth...