
笨办法学python第39节
这节主要讲解的是字典,首先字典和列表的两个区别是:
1. 列表中可以通过数字找到列表中的元素,是数字作为索引的;字典中可以通过任何东西找到想要的元素,即字典可以将一个物件和另外一个东西关联。
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 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()
这一遍出现错误,错误信息如下:
我并没有错误在哪里,然后问八块腹肌,他给我说这个错误很小,但是很难发现,也是我对构造函数不熟悉的结果,解决办法是:def _init_(self, lyrics)这个函数是一个构造函数,init两边是应该分别有两个下划线“_”,但是我只分别打了一个,所以出现错误。
另外我还有一个问题是,这个def __init__(self, lyrics)函数存在的意义,这个函数是一个构造函数,它里面有两个参数self和lyrics,其中这个self是固定的,因为这段函数中的两个函数def都是在class类里面,所以相当于是这个类内部的两个函数相互之间的调用,所以后面用到了self.lyrics。
问题解决后我试着用for-loop循环,用到items()函数,我写的代码如下:
song = {
'happy_bday':'Happy birthday to you, I don\'t want to get sued, So I\'ll stop right there',
'bulls_on_parade':'They rally around the family, With pockets full of shells'
} for key, line in song.items():
print line
运行结果是:
可以看到是无序的。