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 一行代码能实现丧心病狂的功能

手头有 109 张头部 CT 的断层扫描图片,我打算用这些图片尝试头部的三维重建。基础工作之一,就是要把这些图片数据读出来,组织成一个三维的数据结构(实际上是四维的,因为每个像素有 RG...

Python操作json的方法实例分析

Python操作json的方法实例分析

本文实例讲述了Python操作json的方法。分享给大家供大家参考,具体如下: python中对json操作方法有两种,解码loads()和编码dumps() 简单来说: impor...

Python sklearn KFold 生成交叉验证数据集的方法

源起: 1.我要做交叉验证,需要每个训练集和测试集都保持相同的样本分布比例,直接用sklearn提供的KFold并不能满足这个需求。 2.将生成的交叉验证数据集保存成CSV文件,而不是直...

Python urls.py的三种配置写法实例详解

urls.py的配置写法一般有三种方式。 1. 第一种是导入视图的方式,就是 The Django Book 里面样例的写法: from blog.views import inde...

python读取指定字节长度的文本方法

软件版本 Python 2.7.13; Win 10 场景描述 1、使用python读取指定长度的文本; 2、使用python读取某一范围内的文本。 Python代码 test.txt文...