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程序设计的学习有一定的借鉴价值。

相关文章

ubuntu安装sublime3并配置python3环境的方法

最近有一些烦,虚拟机跑代码,跑着跑着存储不够,我就去扩大磁盘,结果虚拟机崩了,试了一上午的修复办法,仍然无法修复,于是只能重装虚拟机,配置各种环境,这里总结一下Ubuntu中配置subl...

python 执行shell命令并将结果保存的实例

方法1: 将shell执行的结果保存到字符串 def run_cmd(cmd): result_str='' process = subprocess.Popen(cmd, sh...

Python实现读取Properties配置文件的方法

本文实例讲述了Python实现读取Properties配置文件的方法。分享给大家供大家参考,具体如下: JAVA本身提供了对于Properties文件操作的类,项目中的很多配置信息都是放...

django基础之数据库操作方法(详解)

django基础之数据库操作方法(详解)

Django 自称是“最适合开发有限期的完美WEB框架”。本文参考《Django web开发指南》,快速搭建一个blog 出来,在中间涉及诸多知识点,这里不会详细说明,如果你是第一次接触...

详解python eval函数的妙用

python eval函数功能:将字符串str当成有效的表达式来求值并返回计算结果。 函数定义: eval(expression, globals=None, locals=Non...