Python语法错误2.7.4

2024-04-25 07:29:23 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码有语法错误。为什么歌曲不被视为一个属性?你知道吗

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

错误:

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'

Tags: 代码selfapple属性objectsongdefmusic
1条回答
网友
1楼 · 发布于 2024-04-25 07:29:23

您将方法初始值设定项命名错误:

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前后的双下划线。你知道吗

演示:

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

相关问题 更多 >