Python语法错误2.7.4

时间:2014-05-28 21:51:51

标签: python python-2.7

我的代码出现了语法错误。为什么歌曲不被视为属性?

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'

1 个答案:

答案 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