pyhton学习日记(三)

容器类型的协议(啥玩意听不懂,先搁这)fromkey,getitem,iteration,generator

总任务:创建一个数组类,且记录读取元素的次数

fromkey的用法

向字典中加入元素,seq是字,value是赋给的值

1
2
3
4
5
6
7
8
9
10
11
12
#语法:dict.fromkeys(seq[, value])

seq = ('Google', 'Runoob', 'Taobao')

dict = dict.fromkeys(seq)
print "新字典为 : %s" % str(dict)

dict = dict.fromkeys(seq, 10)
print "新字典为 : %s" % str(dict)
运行:
新字典为 : {'Google': None, 'Taobao': None, 'Runoob': None}
新字典为 : {'Google': 10, 'Taobao': 10, 'Runoob': 10}

getitem的用处

当实例对象通过[]运算符取值时,会调用它的方法getitem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#语法: __getitem__(self,key)
class DataBase:
'''Python 3 中的类'''

def __init__(self, id, address):
'''初始化方法'''
self.id = id
self.address = address
self.d = {self.id: 1,
self.address: "192.168.1.1",
}

def __getitem__(self, key):
# return self.__dict__.get(key, "100")
return self.d.get(key, "default")#返回键值,没有就返回default
运行:
>>>data = DataBase(1, "192.168.2.11")
>>>print(data["hi"])
default
>>>print(data[data.id])
1

最终的模块(就是这么简单)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class CountList:
def __init__(self,*args):
self.values=[x for x in args]
self.count={}.fromkeys(range(len(self.values)),0)

def __len__(self):
return len(self.values)

def __getitem__(self,key):#??get不行ma ?
self.count[key]+=1
return self.values[key]
运行:
>>> c1=CountList(1,3,5,7,9)
>>> c2=CountList(2,4,6,8,10)
>>> c1[1]
3
>>> c1.count
{0: 0, 1: 1, 2: 0, 3: 0, 4: 0}

迭代器

iter,next

1
2
3
4
5
6
>>> string='xyz'
>>> it iter(string)
>>> while True:
try:print(next(it))
except StopIteration:
break

生成器

yeild

1
2