ex39
代码
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()
运行结果
"C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week three/ex39.py"
Happy birthday to youI don't want to get sued
So I'll stop right there
They rally around the family
With pockets full of shells
Process finished with exit code 0
列表和字典有何不同?
列表是有序排列的一些物件,而字典是将一些物件( keys )对应到另外一些物件( values )的数据结构。
字典能用在哪里?
各种你需要通过某个值去查看另一个值的场合。其实你可以把字典当做一个“查询表”。
列表能用在哪里?
列表是专供有序排列的数据使用的。你只要知道索引就能查到对应的值了。
有没有办法弄一个可以排序的字典?
看看 Python 里的 collections.OrderedDict 数据结构。上网搜索一下文档和用
这章虽然写出来的了,但是没搞懂呀。
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 family",
"With pockets full of shells"])#他们团结在家庭”,“口袋里满是贝壳”
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
代码运行
"C:\Program Files\Python36\python.exe" "D:/小克学习/python/项目/week three/ex40.py"
Happy birthday to you
I don't want to get sued
So I'll stop right there
They rally around family
With pockets full of shells
Process finished with exit code 0
![Upload 图片.png failed. Please try again.]
总结:
这一章没怎么理解,所以专门抄下笔记,准备没事看看,帮助自己理解。
为什么创建 init 或者别的类函数时需要多加一个 self 变量?
如果你不加 self , cheese = 'Frank' 这样的代码意义就不明确了,它指的既可能
是实例的 cheese 属性,或者一个叫做 cheese 的局部变量。有了 self.cheese =
'Frank' 你就清楚地知道了这指的是实例的属性 self.cheese 。
EX41
代码
##Animal is object ( yes , sort of confusing) look at the extra credit #动物是对象(是的,有点迷惑)看额外的信用等级动物(对象):
class Animal(object):
pass
## ??
class Dog(Animal):
def __init__(self, name):
## ??
self.name = name
## ??
class Cat(Animal):
def __init__(self, name):
## ??
self.name = name
## ??
class Person(object):#人(对象)
def __init__(self, name):
## ??
self.name = name
## Prson has-a pet of some kind
self.pet = None
## ??
class Employee(Person):#雇员(人)
def __init__(self, name, salary):
## ?? hmm what is this strange magic?
super(Employee, self).__init__(name)
## ??
self.salary = salary
## ??
class Fish(object):
pass
## ??
class Salmon(Fish):
pass
## ??
class Halibut(Fish):
pass
## rover is-a Dog
rover = Dog("Rover")
## ??
satan = Cat("Satan")
## ??
mary = Person("Mary")
## ??
网友评论