推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
invite
V2EX  ›  Python

Python 初学者关于 super 一问 ( Python 2.7)

  •  
  •   invite · Feb 9, 2015 · 5289 views
    This topic created in 4154 days ago, the information mentioned may be changed or developed.

    class A(object):
    def init( self , name ):
    super(object, self).init()
    self.name = name

    class B(A):
    def init( self , name , birth ):
    super(A , self).init( name )
    self.birth = birth

    我实例化A的时候,没有报错。
    但是实例化B的时候,却报错: TypeError: object.init() takes no parameters
    难道B里面的super方法,直接去调用object的?绕过A了?

    网上搜了什么MRO啥的,但也想不通为什么这里会直接去object了。

    还是我这个写法有问题?

    6 replies    2015-02-09 17:44:56 +08:00
    zhyu
        1
    zhyu  
       Feb 9, 2015
    super 用法错了,class A 里应该是 super(A, self).__init__(),class B 依此类推
    Cynic222
        2
    Cynic222  
       Feb 9, 2015
    super(A , self).init( name ) 你要的是A的父类。。。
    invite
        3
    invite  
    OP
       Feb 9, 2015
    @Cynic222 啊,好像是搞错了。
    zerh925
        4
    zerh925  
       Feb 9, 2015
    class A(object):
    def __init__(self, name):
    super(A, self).__init__()
    self.name = name
    zerh925
        5
    zerh925  
       Feb 9, 2015
    回复不支持markdown吗?
    hahastudio
        6
    hahastudio  
       Feb 9, 2015
    super() 之所以 super 是因为通常你不需要知道 一个类的父类是哪些
    https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4587 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 04:04 · PVG 12:04 · LAX 21:04 · JFK 00:04
    ♥ Do have faith in what you're doing.