习题40 模块、类和对象

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

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

详细的还是看书吧


先给源代码

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

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

bulls_on_parade.sing_me_a_song() # 唱 bulls_on_parade

ju_hua_tai.sing_me_a_song() # 唱菊花台

ju_hua_tai.test_print() #如果不加 ju_hua_tai 会怎么样?

# test_print()            会提示出错,test_print 未定义,这一行注释掉
# 也就是说,要调用类里面的函数,先要把 Song 给一个变量,然后用  变量.类函数  这样的形式来运行



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值