鱼C论坛

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

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

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

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

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

x
  1. class Song(object):
  2.     def _init_(self,lyrics):
  3.         self.lyrics=lyrics
  4.     def sing_me_a_song(self):
  5.         for line in self.lyrics:
  6.             print(line)
  7.     happy_bday=Song(["Happy birthday to you.",
  8.                     "I don't want to get used.",
  9.                     "So I'll stop right there"])
  10.     bulls_on_parade=Song(["They rally around the family",
  11.                          "With pockets full of shells"])
  12.    
  13.     happy_bday.sing_me_a_song()
  14.     bulls_on_parade.sing_me_a_song()
复制代码


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

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

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

所以,你应该将你的代码修改为以下形式:

  1. class Song(object):
  2.     def __init__(self, lyrics):
  3.         self.lyrics = lyrics

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

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

  10. bulls_on_parade = Song(["They rally around the family",
  11.                         "With pockets full of shells"])
  12.    
  13. happy_bday.sing_me_a_song()
  14. bulls_on_parade.sing_me_a_song()
复制代码


这样就应该能解决你的问题。如果有其他问题,欢迎随时向我提问。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

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

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

所以,你应该将你的代码修改为以下形式:

  1. class Song(object):
  2.     def __init__(self, lyrics):
  3.         self.lyrics = lyrics

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

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

  10. bulls_on_parade = Song(["They rally around the family",
  11.                         "With pockets full of shells"])
  12.    
  13. happy_bday.sing_me_a_song()
  14. bulls_on_parade.sing_me_a_song()
复制代码


这样就应该能解决你的问题。如果有其他问题,欢迎随时向我提问。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

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

感谢~!
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-28 02:11

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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