本节讲述了类,模块是什么东西
不过看起来是推荐使用类?
详细的还是看书吧
先给源代码
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 给一个变量,然后用 变量.类函数 这样的形式来运行