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

相关文章

pytorch 归一化与反归一化实例

ToTensor中就有转到0-1之间了。 # -*- coding:utf-8 -*- import time import torch from torchvisi...

numpy数组广播的机制

numpy数组广播的机制

numpy数组的广播功能强大,但是也同时让人疑惑不解,现在让我们来谈谈其中的原理。 广播原则: 如果两个数组的后缘维度(即:从末尾开始算起的维度)的轴长相符或其中一方的长度为1,则认为它...

python 实现快速生成连续、随机字母列表

0.摘要 本文介绍了生成连续和随机字母表的方法,用于快速生成大量字母数据。 主要使用chr()函数,将数字通过ASCII表转换为相应字母。 1.chr() 函数 chr() 用一个范围在...

windows10下python3.5 pip3安装图文教程

windows10下python3.5 pip3安装图文教程

最近Google官方的开发者博客中宣布新的版本Tensorflow(0.12)将增加对Windows的支持,想试着windows10下学习tensorflow,之前已经安装anacond...

Python list列表中删除多个重复元素操作示例

本文实例讲述了Python list列表中删除多个重复元素操作。分享给大家供大家参考,具体如下: 我们以下面这个list为例,删除其中所有值为6的元素: l=[9,6,5,6,6,7...