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

yipeiwu_com7年前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回调函数中使用多线程的方法

下面的demo是根据需求写的简单测试脚本 #!/usr/bin/env python # coding: utf-8 # 第一个列表为依赖组件和版本号,后面紧跟负责人名称 # 接着出...

Python cookbook(数据结构与算法)字典相关计算问题示例

本文实例讲述了Python cookbook(数据结构与算法)字典相关计算问题。分享给大家供大家参考,具体如下: 问题:在字典上对数据执行各式各样的计算(比如求最小值、最大值、排序)。...

解决安装python3.7.4报错Can''t connect to HTTPS URL because the SSL module is not available

解决安装python3.7.4报错Can''t connect to HTTPS URL because the SSL module is not available

简述 从官网下载了Python3.7.4,直接编译安装后,使用pip3出现了报错信息: Can't connect to HTTPS URL because the SSL module...

python3 tkinter实现点击一个按钮跳出另一个窗口的方法

python3 tkinter实现点击一个按钮跳出另一个窗口的方法

如下所示: #-*- encoding:utf-8 -*- from tkinter import * root = Tk() def create(): top = To...

解决Python运行文件出现out of memory框的问题

解决Python运行文件出现out of memory框的问题

爬虫过程中,发现pycharm变得非常卡,然后出现了这个框: 原本想的是4G内存不够,带不动程序,要加内存条。然后发现图中三个对话框的数字都可以改动,感叹号右边也说please inc...