|
20鱼币
关于小甲鱼的程序,我有几个问题:
1.为什么初始化的时候还要用super().__init__(org),而且几乎后面的每个魔法方法和函数都用到了super()
2.为什么有的膜法方法和函数中有 return 有的没有return
3.在用count方法的时候,为什么函数的名字是counter()而不用count这个函数名
4.index这个方法为什么没有重新定义这个函数就可以直接用
以下是小甲鱼的代码
- class CountList(list):
- def __init__(self, *args):
- super().__init__(args)
- self.count = []
- for i in args:
- self.count.append(0)
- def __len__(self):
- return len(self.count)
- def __getitem__(self, key):
- self.count[key] += 1
- return super().__getitem__(key)
- def __setitem__(self, key, value):
- self.count[key] += 1
- super().__setitem__(key, value)
- def __delitem__(self, key):
- del self.count[key]
- super().__delitem__(key)
- def counter(self, key):
- return self.count[key]
- def append(self, value):
- self.count.append(0)
- super().append(value)
- def pop(self, key=-1):
- del self.count[key]
- return super().pop(key)
- def remove(self, value):
- key = super().index(value)
- del self.count[key]
- super().remove(value)
- def insert(self, key, value):
- self.count.insert(key, 0)
- super().insert(key, value)
- def clear(self):
- self.count.clear()
- super().clear()
- def reverse(self):
- self.count.reverse()
- super().reverse()
复制代码
(PS 学膜法方法都学懵了,有没有大神有没有什么诀窍的?)
1. 需要调用父类(即 list)的初始化方法 __init__()。
2. 需要 return 的才 return。比如 __getitem__,用户是想获取序列指定的元素,就需要 return。但是对于 __setitem__,用户只是想设置序列中指定的元素,并不想要返回值。
3. 因为自身有 count 属性,定义 count 方法将会覆盖 count 属性,导致程序错误。
4. 因为 CountList 继承自 list,而 list 有 index 这个方法,所以可以直接使用 index。
|
最佳答案
查看完整内容
1. 需要调用父类(即 list)的初始化方法 __init__()。
2. 需要 return 的才 return。比如 __getitem__,用户是想获取序列指定的元素,就需要 return。但是对于 __setitem__,用户只是想设置序列中指定的元素,并不想要返回值。
3. 因为自身有 count 属性,定义 count 方法将会覆盖 count 属性,导致程序错误。
4. 因为 CountList 继承自 list,而 list 有 index 这个方法,所以可以直接使用 index。
|