笨办法学python第39节 

这节主要讲解的是字典,首先字典和列表的两个区别是:

1. 列表中可以通过数字找到列表中的元素,是数字作为索引的;字典中可以通过任何东西找到想要的元素,即字典可以将一个物件和另外一个东西关联。

2. 列表是有顺序的;字典是无序的。(上一节有提到)

本节的代码如下:

 1 class Song(object):
 2 
 3     def _init_(self, lyrics):
 4         self.lyrics = lyrics
 5 
 6     def sing_me_a_song(self):
 7         for line in self.lyrics:
 8             print line
 9 
10 happy_bday = Song(["Happy birthday to you",
11                 "I don't want to get sued",
12                 "So I'll stop right there"])
13 
14 bulls_on_parade = Song(["They rally around the family",
15                     "With pockets full of shells"])
16 
17 happy_bday.sing_me_a_song()
18 
19 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()函数,我写的代码如下:

1 song = {
2     'happy_bday':'Happy birthday to you, I don\'t want to get sued, So I\'ll stop right there',
3     'bulls_on_parade':'They rally around the family, With pockets full of shells'
4 }
5 
6 for key, line in song.items():
7     print line

运行结果是:

可以看到是无序的。

 posted on 2016-09-24 21:08  Eiffel最爱八块腹肌  阅读(348)  评论(0编辑  收藏  举报