|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
大家好!我对【第47讲 定制序列】 里的程序有疑问,请大家解答,谢谢!!!
下面的代码是笔记里原封不动的代码:
###########################
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):
self.count[key] += 1
return self.values[key]
c = CountList( 'zero', 'one', 'two' )
###########################
然后我的问题是之后的操作:
1.键入 c[index] 为何不报错(比如键入c[0])?我认为ta会报错是因为我认为c不是列表(也不是元组或字符串),所以c不可以跟下标。但事实证明我是错的,但我不明白为什么我错了,请指出我错误的地方。还有,是哪个语句赋予了c可以直接跟下标的能力?
2.键入 c.values[0] 能正常显示结果 ‘zero’,但用此方法的话c.count就不会增加。初级小白都会使用c.values[index]去读取列表里的数据吧,因为c.values才是列表嘛。我明白__getitem__(self,key)只有在self[key]的时候才会触发,也就是在c[index]的时候才能触发,那么c[index]会使c.count增加1,而c.values[index]不会使c.count增加1,这算不算程序的bug?如何修复?
谢谢!
2.键入 c.values[0] 能正常显示结果 ‘zero’,但用此方法的话c.count就不会增加。初级小白都会使用c.values[index]去读取列表里的数据吧,因为c.values才是列表嘛。我明白__getitem__(self,key)只有在self[key]的时候才会触发,也就是在c[index]的时候才能触发,那么c[index]会使c.count增加1,而c.values[index]不会使c.count增加1,这算不算程序的bug?如何修复? - lass CountList:
- def __init__(self, *args):
- self.__values = args
- self.count = dict.fromkeys(range(len(args)), 0)
- def __len__(self):
- return len(self.__values)
- def __getitem__(self, key):
- self.count[key] += 1
- return self.__values[key]
- c = CountList( 'zero', 'one', 'two' )
复制代码
|
|