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

2013-09-21 14:43:42 +08:00
 ybooty
代码如下

#! /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'
3115 次点击
所在节点    Python
5 条回复
9hills
2013-09-21 14:54:47 +08:00
python里面 是__init__
不是_init_

两个下划线
ybooty
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
2013-09-21 15:29:34 +08:00
把super(Songbird, self).__init__() 改为 bird.__init()的方法就可以成功,为什么前者就出问题..
ybooty
2013-09-21 15:31:28 +08:00
问题已经解决
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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/83169

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX