推荐学习书目
› 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
ybooty
V2EX  ›  Python

新手python求各位解答个简单的问题

  •  
  •   ybooty ·
    kidbai · Sep 21, 2013 · 4429 views
    This topic created in 4757 days ago, the information mentioned may be changed or developed.
    代码如下

    #! /usr/bin/env python
    _metaclass_ = type

    class bird:
    def _init_(self):
    self.hungry = True
    def eat(self):
    if self.hungry:
    print 'I am hungry'
    self.hungry = False
    else:
    print 'No,thanks'
    class Songbird(bird):
    def _init_(self):
    super(Songbird, self)._init_()
    self.sound = 'Squawk!'
    def sing(self):
    print self.sound

    a = Songbird()
    a.sing()
    a.eat()
    a.eat()

    错误信息:

    Traceback (most recent call last):
    File "bird.py", line 21, in <module>
    a.sing()
    File "bird.py", line 18, in sing
    print self.sound
    AttributeError: Songbird instance has no attribute 'sound'
    5 replies  •  1970-01-01 08:00:00 +08:00
    9hills
        1
    9hills  
       Sep 21, 2013   ❤️ 1
    python里面 是__init__
    不是_init_

    两个下划线
    ybooty
        2
    ybooty  
    OP
       Sep 21, 2013
    @9hills 修改后
    Traceback (most recent call last):
    File "bird.py", line 20, in <module>
    sb = Songbird()
    File "bird.py", line 15, in __init__
    super(Songbird, self).__init__()
    TypeError: must be type, not classobj
    ybooty
        3
    ybooty  
    OP
       Sep 21, 2013
    把super(Songbird, self).__init__() 改为 bird.__init()的方法就可以成功,为什么前者就出问题..
    ybooty
        4
    ybooty  
    OP
       Sep 21, 2013
    问题已经解决
    9hills
        5
    9hills  
       Sep 21, 2013
    @ybooty
    super() cannot be used with old-style class

    Python定义类有两种方法,调用父类初始化函数也有两种方法。

    class A: 这是旧的定义方法
    class A(object): 所有的类必须有父类,也就是bird类必须这么定义: class bird(object):
    这是新的定义方法,只有新类型的类才能用super来init
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   865 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 19:34 · PVG 03:34 · LAX 12:34 · JFK 15:34
    ♥ Do have faith in what you're doing.