当你看到像 mystuff.append('hello')
这样的代码时,你事实上已经在 Python 内部激发了一个连锁反应。以下是它的工作原理:
-
Python 看到你用到了
mystuff
,于是就去找到这个变量。也许它需要倒着检查看你有没有在哪里用=
创建过这个变量,或者检查它是不是一个函数参数,或者看它是不是一个全局变量。不管哪种方式,它得先找到mystuff
这个变量才行。 -
一旦它找到了
mystuff
,就轮到处理句点.
(period) 这个操作符,而且开始查看mystuff
内部的一些变量了。由于mystuff
是一个列表,Python 知道 mystuff 支持一些函数。 -
接下来轮到处理
append
。Python 会将append
和mystuff
支持的所有函数的名称一一对比,如果确实其中有一个叫append
的函数,那么 Python 就会去使用这个函数。 -
接下来 Python 看到了括号
(
,并且意识到, “噢,原来这是一个函数”,到了这里,它就正常会调用这个函数了,不过这里的函数还要多一个参数才行。 -
这个额外的参数其实是……
mystuff
! 你会觉得很奇怪对不对?不过这就是 Python 的工作原理,记住它就行了。所以到最后真正发生的事情其实是append(mystuff, 'hello')
,不过你所看到的mystuff.append('hello')
。
——————————————————————————————————————————
练习38
len函数的作用,若len函数的对象是字符串,则返回字符串长度,若对象为列表,则返回列表中元素个数。
先用split把句子切开,每个单词即为列表中的元素,然后使用pop函数把more_stuff的元素给到next_one中
pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值,如此直到stuff中元素个数等于10。while的布尔值为false,停止循环
ten_things = "Apples Oranges Crows Telephone Light Sugar"
print("Wait there are not 10 things in that list. Let's fix it")
stuff = ten_things.split(' ')
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"]
while len(stuff) != 10:
next_one = more_stuff.pop()
print("Adding:", next_one)
stuff.append(next_one)
print(f"There are {len(stuff)} items now.")
print("There we go:",stuff)
print("Let's do some things with tuff.")
print(stuff[1])
print(stuff[-1])#whoa! fancy
print(stuff.pop())
print(' '.join(stuff))#what?cool!
print('#'.join(stuff[3:5]))#super stellat!
在最下方的print中,展示了怎么输出list中元素的方法,正序,倒序,提取一个,join即为使用前面引号中的符号来连接,stuff[3:5]为输出顺序为3≤x<5的元素。
———————————————————————————————————————————
练习39 字典
字典应该说是建立映射关系,像这样
>>> stuff = {'name': 'Zed', 'age': 39, 'height': 6 * 12 + 2}
>>> print(stuff['name'])
Zed
>>> print(stuff['age'])
39
>>> print(stuff['height'])
74
>>> stuff['city'] = "SF"
>>> print(stuff['city'])
SF
py39中的例子为州和城市,print中通过打印字典函数的方式来调用字典中的映射,同时字典也支持嵌套,如下例中states['Michigan']返回的值是MI,到上一级调用了cities['mi']
# create a basic set of states and some cities in them
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}
# add some more cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
print("NY State has: ", cities['NY'])
print("Michigan has: ", cities[states['Michigan']])
items() 函数以列表返回可遍历的(键, 值) 元组数组。
因为list是一个映射,所以他应该对应两个值,第一个a赋给state,第一个a对应的映射赋给abbrev,即有了第一句print,同样的,也可以用调用映射的形式来输出。
print('-' * 10)
for state, abbrev in list(states.items()):
print(f"{state} state is abbreviated {abbrev}")
print(f"and has city {cities[abbrev]}")
——————————————————————————————————————————
练习40
1.字典中映射的用法
2.导入脚本,使用脚本中的函数
import mystuff
#导入脚本中的文件
mystuff.apple()
print(mystuff.tangerine)
.apple()调用mystuff中的apple函数,即如下
def apple():
print("I AM APPLES!")
直接在屏幕上打出这个,前面说明他是mystuff中的apple()函数,即前文所说的,apple函数没有变量,apple(stuff, ),直接print
I AM APPLES!
第二句则是print一个变量,他来自mystuff,直接print
tangerine = "living reflection of a dream"
3.建立类的概念
class Mystuff(object):
def __init__ (self):
self.tangerine = "And now a thousand years between"
def apple(self):
print("I AM CLASSY APPLES!")
thing = Mystuff()
#thing = ....调用class Mystuff
thing.apple()
print(thing.tangerine)
这个先强行记下来吧,暂时没办法全部理解,我的理解是mystuff(object)是属于object的一个类,在这个类中有一个空的 init 函数和自己定义的apple函数,对于init初始化函数,当变量继承了这个类后,他将拥有这个类中的function。可以这么理解
thing=Mystuff()#对其进行赋值,继承
print(thing.tangerine)中,thing就是self,self.tangerine 的值传递给了 thing.tangerine,打印出来就是那句歌词。
为什么我在类下面用 init
函数或者其他函数的时候要用 self
? 如果你不用 self
,那么像 cheese = 'Frank'
这样的代码就会很含糊,计算机不知道你是指实例的 cheese 属性还是 一个叫做 cheese 的局部变量。而用 self.cheese = 'Frank'
的话就会很清晰,你是指实例的属性 self.cheese
。
关于为什么init(self)的理解如上。对于ex40.py 进行分析
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 tha family",
"With pockets full of shells"])
happy_bday.sing_me_a_song()
bulls_on_parade.sing_me_a_song()
给了两首歌,一个是三行一个是两行,分别调用S_M_A_S函数,在对于两首歌进行赋值内容输入的时候,已经将类的属性继承过去了,而在singmeasong函数中只有line一个变量,self.lyrics对于两首歌分别是他们的歌词,即happy_bday.lyrics和bulls_on_parade.lyrics,好吧,这个练习先这样。