我的代码出现了语法错误。为什么歌曲不被视为属性?
class MyStuff(object):
def _ini_(self):
self.song = "Hey Brother"
def apple(self):
print "I got a iphone"
music = MyStuff()
music.apple()
print music.song
ERROR:
I got a iphone
Traceback (most recent call last):
File "main.py", line 9, in
print music.song
AttributeError: 'MyStuff' object has no attribute 'song'
答案 0 :(得分:3)
您错误地命名了方法初始值设定项:
def _ini_(self):
在创建实例时会自动调用不。因此,永远不会创建song
属性,稍后尝试访问该属性会导致AttributeError
例外。
将其命名为__init__
:
class MyStuff(object):
def __init__(self):
self.song = "Hey Brother"
def apple(self):
print "I got a iphone"
请注意单词init
之前和之后的 double 下划线。
演示:
>>> class MyStuff(object):
... def __init__(self):
... self.song = "Hey Brother"
... def apple(self):
... print "I got a iphone"
...
>>> music = MyStuff()
>>> music.apple()
I got a iphone
>>> print music.song
Hey Brother