习题40 模块、类和对象

来源:互联网 发布:淘宝晚装短款晚礼服 编辑:程序博客网 时间:2024/05/02 01:31

本节讲述了类,模块是什么东西

不过看起来是推荐使用类?

详细的还是看书吧


先给源代码

class Song(object):    def __init__(self, lyrics):        self.lyrics = lyrics    def sing_me_a_song(self):        for line in self.lyrics:            print  linehappy_bday = Song(["Happy birthday to you",                   "I don't want to get sued",                   "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()


运行结果如下:


==================================================================================

附加习题

1-4

# -*- coding:utf-8 -*-class Song(object): # 创建一个类    def __init__(self, lyrics): # 类函数括号里面最好加上self变量,init 应该是初始化,后面习题会有吧        self.lyrics = lyrics    def sing_me_a_song(self): # 创建唱歌函数        for line in self.lyrics: # 循环每行                       print line # 打印每行        def test_print(self):        for i in range(0,6):            print ihappy_bday = Song(["Happy birthday to you",                   "I don't want to get sued",                   "So I'll stop right there"])ju_hua_tai = Song(["菊花残 满地伤 ","你的笑容已泛黄","花落人断肠 我心事静静躺", "北风乱 夜未央","你的影子剪不断", "徒留我孤单在湖面 成双"])bulls_on_parade = Song(["They rally around the family",                        "With pockets full of shells"])happy_bday.sing_me_a_song() # 唱 happy_bdaybulls_on_parade.sing_me_a_song() # 唱 bulls_on_paradeju_hua_tai.sing_me_a_song() # 唱菊花台ju_hua_tai.test_print() #如果不加 ju_hua_tai 会怎么样?# test_print()            会提示出错,test_print 未定义,这一行注释掉# 也就是说,要调用类里面的函数,先要把 Song 给一个变量,然后用  变量.类函数  这样的形式来运行



0 0
原创粉丝点击