在Python类的方法(method)中,要调用父类的某个方法,在Python 2.2以前,通常的写法如代码段1:
代码段1:
class A:
def __init__(self):
   print "enter A"
   print "leave A"

class B(A):
def __init__(self):
   print "enter B"
   A.__init__(self)
   print "leave B"

>>> b = B()

enter B
enter A
leave A
leave B

即,使用非绑定的类方法(用类名来引用的方法),并在参数列表中,引入待绑定的对象(self),从而达到调用父类的目的。

这样做的缺点是,当一个子类的父类发生变化时(如类B的父类由A变为C时),必须遍历整个类定义,把所有的通过非绑定的方法的类名全部替换过来,例如代码段2,

代码段2:

class B(C):    # A --> C
def __init__(self):
   print "enter B"
   C.__init__(self) # A --> C
   print "leave B"

如果代码简单,这样的改动或许还可以接受。但如果代码量庞大,这样的修改可能是灾难性的。很容易导致修改错误的出现。

因此,自Python 2.2开始,Python添加了一个关键字super,来解决这个问题。下面是Python 2.3的官方文档说明:

super(type[, object-or-type])

Return the superclass of type. If the second argument is omitted the super object
returned is unbound. If the second argument is an object, isinstance(obj, type)
must be true. If the second argument is a type, issubclass(type2, type) must be
true. super() only works for new-style classes.

A typical use for calling a cooperative superclass method is:

class C(B):
       def meth(self, arg):
           super(C, self).meth(arg)

New in version 2.2.

从说明来看,可以把类B改写如代码段3:

代码段3:

class A(object):    # A must be new-style class
def __init__(self):
   print "enter A"
   print "leave A"

class B(C):     # A --> C
def __init__(self):
   print "enter B"
   super(B, self).__init__()
   print "leave B"

尝试执行上面同样的代码,结果一致,但修改的代码只有一处,把代码的维护量降到最低,是一个不错的用法。因此在我们的开发过程中,super关键字被大量使用,而且一直表现良好。

最新文章

  1. vim保存文件时,生成.un~文件
  2. static成员变量与返回对象的引用
  3. UML-用例图
  4. 用python的BeautifulSoup分析html 【转】
  5. Windows下配置Tomcat服务器
  6. CC2540开发板学习笔记(九)—— BLE协议简介
  7. poj1703 Lost Cows
  8. 课堂所讲整理:super和转型(修改版)
  9. Ubuntu工具:vi编辑器
  10. STL 案例分析
  11. 【宽搜】Vijos P1206 CoVH之再破难关
  12. Mysql Binlog日志详解
  13. Python打印格式化与字符串
  14. Fork别人的代码 原作者更新后如何同步
  15. urllib库详解 --Python3
  16. django中 自定义User报错 已经注册的错误
  17. Angularjs演示Service功能
  18. bzoj2152 / P2634 [国家集训队]聪聪可可(点分治)
  19. sun.misc.BASE64Encoder图片编码,并在页面显示
  20. ProBase

热门文章

  1. anaconda环境变量+修改jupyter默认路径
  2. POJ 2109 巧妙解法
  3. SQL Server 调优系列进阶篇 - 如何重建数据库索引
  4. ZOJ 3822 Domination 概率dp 难度:0
  5. 51nod1210
  6. 猎豹浏览器(chrome内核)屏蔽视频广告
  7. python 爬虫系列教程方法总结及推荐
  8. Linux C:access()时间条件竞争漏洞
  9. 多种数据库之间的同步工具SymmetricDS
  10. SSH项目搭建(五)——web.xml文件配置