V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2015-02-09 16:43:59 +08:00 · 4566 次点击
    这是一个创建于 3362 天前的主题,其中的信息可能已经有所发展或是发生改变。

    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 条回复    2015-02-09 17:44:56 +08:00
    zhyu
        1
    zhyu  
       2015-02-09 16:55:35 +08:00
    super 用法错了,class A 里应该是 super(A, self).__init__(),class B 依此类推
    Cynic222
        2
    Cynic222  
       2015-02-09 16:58:41 +08:00
    super(A , self).init( name ) 你要的是A的父类。。。
    invite
        3
    invite  
    OP
       2015-02-09 17:01:23 +08:00
    @Cynic222 啊,好像是搞错了。
    zerh925
        4
    zerh925  
       2015-02-09 17:31:53 +08:00
    class A(object):
    def __init__(self, name):
    super(A, self).__init__()
    self.name = name
    zerh925
        5
    zerh925  
       2015-02-09 17:33:21 +08:00
    回复不支持markdown吗?
    hahastudio
        6
    hahastudio  
       2015-02-09 17:44:56 +08:00
    super() 之所以 super 是因为通常你不需要知道 一个类的父类是哪些
    https://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5475 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 01:26 · PVG 09:26 · LAX 18:26 · JFK 21:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.