
环境为 python3.5,ubuntu1604 看到一个库中对 list 做了继承 代码大意如下
在看前人代码的时候发现对方使用 NewList([1,2,3], 3)['total']这类语法获得正确输出 但 l = NewList([1,2,3], 3)后 l.total 是正确输出的 l['total']是报错得:list indices must be integers or slices 不知道应该怎么解释这种情况
class NewList(list): def __init__(self, iterable=None, _total=0): if iterable is not None: list.__init__(self, iterable) else: list.__init__(self) self.total = _total self.iterable = iterable or [] next = __next__ 1 geebos PRO 我试了一下,第一种也是报错的 |
2 wangyzj OP |
3 ManjusakaL 2021-01-11 19:41:40 +08:00 你试一下 ```python a = list() a['total'] ``` 不就懂了。。 要理解的更清楚去背诵一下 Python Document 中 Language Reference Chap 3 Data Model 这章你就懂了 |
4 skinny 2021-01-11 19:47:47 +08:00 你这既不是 mapping 对象也没有实现自己的__getitem__方法当然会报错,tutorial 多读几遍…… |
5 simple2025 2021-01-11 20:07:20 +08:00 感觉是复写了 __getitem__, .的写法需要 override __getattr__吧 |
6 nthhdy 2021-01-11 20:10:40 +08:00 > 在看前人代码的时候发现对方使用 NewList([1,2,3], 3)['total']这类语法获得正确输出 不应该吧,再读读,真实运行一下。看是不是理解有误。如果这里的 NewList 真是像贴出来的代码这样定义的,这个表达式同样会报错的。 |
7 wangyzj OP @nthhdy #6 但是如果有了 getitem 实现的话不应该单独赋值一个新的 var 后执行['total']报错 |
8 zhanglintc 2021-01-11 21:10:16 +08:00 想想不应该会发生这种现象啊, 无论 `NewList()` 产生的对象是否赋值给 `l`, 它都是同一个类型的 `NewList` 对象, 不应该影响它的属性调用方式什么的. 如果你给的例子的输出的确没有问题的话, 那这倒是个挺有意思的问题. 楼主可以再运行下贴点结果证明的确是这个现象么. |