Python中的super()方法使用简介

yipeiwu_com5年前Python基础

子类里访问父类的同名属性,而又不想直接引用父类的名字,因为说不定什么时候会去修改它,所以数据还是只保留一份的好。其实呢,还有更好的理由不去直接引用父类的名字,
这时候就该super()登场啦——

class A:
 def m(self):
  print('A')

class B(A):
 def m(self):
  print('B')
  super().m()

B().m()

当然 Python 2 里super() 是一定要参数的,所以得这么写:

class B(A):
 def m(self):
  print('B')
  super(B, self).m()

    super在单继承中使用的例子:

class Foo():
  def __init__(self, frob, frotz)
    self.frobnicate = frob
    self.frotz = frotz

class Bar(Foo):
  def __init__(self, frob, frizzle)
    super().__init__(frob, 34)
    self.frazzle = frizzle

此例子适合python 3.x,如果要在python2.x下使用则需要稍作调整,如下代码示例:

class Foo(object): 
  def __init__(self, frob, frotz): 
    self.frobnicate = frob 
    self.frotz = frotz 

class Bar(Foo): 
  def __init__(self, frob, frizzle): 
    super(Bar,self).__init__(frob,34) 
    self.frazzle = frizzle 

new = Bar("hello","world") 
print new.frobnicate 
print new.frazzle 
print new.frotz 

需要提到自己的名字。这个名字也是动态查找的,在这种情况下替换第三方库中的类会出问题。

`super()`` 很好地解决了访问父类中的方法的问题。

相关文章

python difflib模块示例讲解

python difflib模块示例讲解

difflib模块提供的类和方法用来进行序列的差异化比较,它能够比对文件并生成差异结果文本或者html格式的差异化比较页面,如果需要比较目录的不同,可以使用filecmp模块。 clas...

Python基于Pymssql模块实现连接SQL Server数据库的方法详解

Python基于Pymssql模块实现连接SQL Server数据库的方法详解

本文实例讲述了Python基于Pymssql模块实现连接SQL Server数据库的方法。分享给大家供大家参考,具体如下: 数据库版本:SQL Server 2012。 按照Python...

python出现"IndentationError: unexpected indent"错误解决办法

python出现"IndentationError: unexpected indent"错误解决办法

python出现"IndentationError: unexpected indent"错误解决办法 Python是一种对缩进非常敏感的语言,最常见的情况是tab和空格的混用会导致错误...

python语言线程标准库threading.local解读总结

本段源码可以学习的地方: 1. 考虑到效率问题,可以通过上下文的机制,在属性被访问的时候临时构建; 2. 可以重写一些魔术方法,比如 __new__ 方法,在调用 object.__ne...

numpy.transpose对三维数组的转置方法

如下所示: import numpy as np 三维数组 arr1 = np.arange(16).reshape((2, 2, 4)) #[[[ 0 1 2 3] #...