python中类的一些方法分析

yipeiwu_com6年前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 实现网上商城,转账,存取款等功能的信用卡系统

一、要求 二、思路 1.购物类buy 接收 信用卡类 的信用卡可用可用余额, 返回消费金额 2.信用卡(ATM)类 接收上次操作后,信用卡可用余额,总欠款,剩余欠款,存款 其中: 1...

django数据库自动重连的方法实例

简介 Django数据库连接超过wait_timeout导致连接丢失时自动重新连接数据库 https://github.com/zhanghaofe...(本地下载) 安装 pi...

用Python代码来绘制彭罗斯点阵的教程

用Python代码来绘制彭罗斯点阵的教程

这里是显示彭罗斯点阵的Python的脚本。是的,这是可以运行的有效Phython代码。 译注:彭罗斯点阵,物理学术语。上世纪70年代英国数学家彭罗斯第一次提出了这个概念,称为彭罗斯点阵(...

python-pyinstaller、打包后获取路径的实例

python-pyinstaller、打包后获取路径的实例

使用pyinstaller可以把.py文件打包为.exe可执行文件,命令为: pyinstaller hello.py 打包后有两个文件夹,一个是dist,另外一个是build,可执行文...

Python多进程并发(multiprocessing)用法实例详解

本文实例讲述了Python多进程并发(multiprocessing)用法。分享给大家供大家参考。具体分析如下: 由于Python设计的限制(我说的是咱们常用的CPython)。最多只能...