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统计文件中去重后uuid个数的方法

本文实例讲述了Python统计文件中去重后uuid个数的方法。分享给大家供大家参考。具体如下: 利用正则表达式按行获取日志文件中的的uuid,并且统计这些uuid的去重个数(去重利用se...

Python中使用asyncio 封装文件读写

前言 和网络 IO 一样,文件读写同样是一个费事的操作。 默认情况下,Python 使用的是系统的阻塞读写。这意味着在 asyncio 中如果调用了 f = file('xx'...

python虚拟环境virtualenv的使用教程

virtualenv 是一个创建隔绝的Python环境的工具。virtualenv创建一个包含所有必要的可执行文件的文件夹,用来使用Python工程所需的包。 安装 pip inst...

Python二分法搜索算法实例分析

本文实例分析了Python二分法搜索算法。分享给大家供大家参考。具体分析如下: 今天看书时,书上提到二分法虽然道理简单,大家一听就明白但是真正能一次性写出别出错的实现还是比较难的,即使给...

Python文件读写保存操作的示例代码

记录下第一次使用Python读写文件的过程,虽然很简单,第一次实现其实也有些注意的事项。 单个文件的读操作: 我们先假设一个需求如下: 读取一个test.txt文件 删除指...