鱼C论坛

 找回密码
 立即注册
查看: 1728|回复: 2

[已解决]关于类的问题,报错是未被定义

[复制链接]
发表于 2023-6-14 16:31:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
class Song(object):
    def _init_(self,lyrics):
        self.lyrics=lyrics
    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)
    happy_bday=Song(["Happy birthday to you.",
                    "I don't want to get used.",
                    "So I'll stop right there"])
    bulls_on_parade=Song(["They rally around the family",
                         "With pockets full of shells"])
    
    happy_bday.sing_me_a_song()
    bulls_on_parade.sing_me_a_song()

想知道为什么这里显示name 'Song' is not defined呢,如果想让我的代码跑起来应该怎么修改呢
截图未命名.jpg
最佳答案
2023-6-14 16:39:54
你的代码出现问题主要是有两个原因。

1. Python的初始化函数应该是 __init__ 而不是 _init_ 。你的初始化函数缺少一个下划线。

2. 创建类对象和调用类方法应该在类定义之外进行,而不是在类定义的内部。

所以,你应该将你的代码修改为以下形式:
class Song(object):
    def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)

happy_bday = Song(["Happy birthday to you.",
                   "I don't want to get used.",
                   "So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])
   
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

这样就应该能解决你的问题。如果有其他问题,欢迎随时向我提问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-6-14 16:39:54 | 显示全部楼层    本楼为最佳答案   
你的代码出现问题主要是有两个原因。

1. Python的初始化函数应该是 __init__ 而不是 _init_ 。你的初始化函数缺少一个下划线。

2. 创建类对象和调用类方法应该在类定义之外进行,而不是在类定义的内部。

所以,你应该将你的代码修改为以下形式:
class Song(object):
    def __init__(self, lyrics):
        self.lyrics = lyrics

    def sing_me_a_song(self):
        for line in self.lyrics:
            print(line)

happy_bday = Song(["Happy birthday to you.",
                   "I don't want to get used.",
                   "So I'll stop right there"])

bulls_on_parade = Song(["They rally around the family",
                        "With pockets full of shells"])
   
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()

这样就应该能解决你的问题。如果有其他问题,欢迎随时向我提问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2023-6-14 16:47:23 | 显示全部楼层
isdkz 发表于 2023-6-14 16:39
你的代码出现问题主要是有两个原因。

1. Python的初始化函数应该是 __init__ 而不是 _init_ 。你的初始 ...

感谢~!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-22 19:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表