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
ybooty
V2EX  ›  Python

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

  •  
  •   ybooty ·
    kidbai · 2013-09-21 14:43:42 +08:00 · 3103 次点击
    这是一个创建于 3868 天前的主题,其中的信息可能已经有所发展或是发生改变。
    代码如下

    #! /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 条回复    1970-01-01 08:00:00 +08:00
    9hills
        1
    9hills  
       2013-09-21 14:54:47 +08:00   ❤️ 1
    python里面 是__init__
    不是_init_

    两个下划线
    ybooty
        2
    ybooty  
    OP
       2013-09-21 15:16:36 +08:00
    @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
       2013-09-21 15:29:34 +08:00
    把super(Songbird, self).__init__() 改为 bird.__init()的方法就可以成功,为什么前者就出问题..
    ybooty
        4
    ybooty  
    OP
       2013-09-21 15:31:28 +08:00
    问题已经解决
    9hills
        5
    9hills  
       2013-09-21 20:18:58 +08:00
    @ybooty
    super() cannot be used with old-style class

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

    class A: 这是旧的定义方法
    class A(object): 所有的类必须有父类,也就是bird类必须这么定义: class bird(object):
    这是新的定义方法,只有新类型的类才能用super来init
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3225 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:20 · PVG 22:20 · LAX 07:20 · JFK 10:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.