zoukankan      html  css  js  c++  java
  • 理解python super()类

    首先我们通过网友在stackoverflow关于python super类的一个疑问来作为本篇的开始,问题大致是这样的:

    >>> class A(object):
    ...     def __init__(self):
    ...             print "A init"
    ...             super(A,self).__init__()
    ... 
    >>> 
    >>> a = A()
    A init
    >>> class B(object):
    ...     def __new__(self):
    ...             print "B new"
    ...             super(B,self).__new__()
    ... 
    >>> 
    >>> b = B()
    B new
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 4, in __new__
    TypeError: object.__new__(): not enough arguments
    >>> 

    可以看到如果按照调用super类的__init__()方法一样调用__new__()类,会报错的,报错说参数不够。下面的代码是正确的使用super类的__new__()方法。

    >>> 
    >>> class B(object):
    ...     def __new__(self):
    ...             print "B new"
    ...             super(B,self).__new__(self)
    ... 
    >>> 
    >>> b = B()
    B new
    >>> 

    为什么需要在super类的__new__(self)显示的传递类和类实例?

    因为__new__是一个static method静态方法,静态方法是脱离了类本身之外的一个方法,所以他并没有绑定类(类实例)自己作为隐式参数传递,所以super(...).__new__返回的也是一个static method静态方法。所以需要显示的传递。详细移步阅读 http://www.python.org/download/releases/2.2/descrintro/#__new__

    super()是什么?

    super()是什么? super是一个内建的type。在对象中使用super经常会让人产生错觉,令人认为返回的父类对象。其实不然,实际上他返回的是super类的一个对象。实例化的时候,第一个参数是一个类型(type),第二个参数可以是type的instance实例,也可以是type的subclass。你调用 super(Base, self) 会返回一个 __class__ = super 的对象,这个对象可以作为一个代理,通过BFS的顺序去访问第一个直接定义了目标属性的基类里的属性。实际上并不是非要用self作为super的第二个参数,甚至super并不是必须在class内部才能调用:

    >>> class A(object):
    ...     def foo(self):
    ...             print self.name
    ... 
    >>> class B(A):
    ...     def __init__(self, name):
    ...             self.name = name
    ... 
    >>> b = B('b')
    >>> super(B, b).foo()
    b
    >>> 

    关于静态方法的探讨可以查看我之前的一篇:

    http://www.cnblogs.com/kennyhr/p/3935465.html

    本文参考资料:

    http://segmentfault.com/q/1010000000267263

  • 相关阅读:
    Docker01 centos系统安装、centos安装docker、docker安装mongoDB
    WebFlux03 SpringBoot WebFlux实现CRUD
    WebFlux02 SpringBoot WebFlux项目骨架搭建
    WebFlux01 webflux概念、异步servlet、WebFlux意义
    ReactiveStream03
    ReactiveStream02
    ReactiveStream01
    Stream03
    python爬虫2
    python爬虫1
  • 原文地址:https://www.cnblogs.com/kennyhr/p/3962801.html
Copyright © 2011-2022 走看看