|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 yexing 于 2020-2-3 11:27 编辑
定义一个继承列表的类,重写remove()方法(汇总了常见报错,并进行中文提示),代码如下:
- def Remove(list):
- def __init__(self, *args):
- super().__init__(args)
- def remove(self, *value):
- print("正在调用\".remove()\"方法...")
- if not len(value):
- print("出错啦!要传入一个参数!")
- return
- elif len(value) > 1:
- print("出错啦!最多只能传入一个参数!")
- else:
- if value[0] in self:
- super().remove(value)
- print("成功将元素\"%s\"删除啦~" % value)
- else:
- print("出错啦!传入的元素不存在哦!")
- return
复制代码
运行过程如下:
- >>>a = List(1,2,3,4,5)
- >>>a
- [1,2,3,4,5]
- >>>a.remove(1)
- 正在调用".remove()"方法...
- Traceback (most recent call last):
- File "<pyshell#0>", line 1, in <module>
- a.remove(1)
- File "C:\测试.py", line 14, in remove
- super().remove(value)
- ValueError: list.remove(x): x not in list
复制代码
请问如何修改代码,解决报错问题?
附注:运行时其它报错(比如传入参数错误)均可给予中文提示,只是正确传入参数却报错,问题出在super()函数那块,请问如何修改?
怎么是 def Remove(list) 呢。。。将第 14 行的 value 改成 value[0]。
- class Remove(list):
- def __init__(self, *args):
- super().__init__(args)
- def remove(self, *value):
- print("正在调用".remove()"方法...")
- if not len(value):
- print("出错啦!要传入一个参数!")
- return
- elif len(value) > 1:
- print("出错啦!最多只能传入一个参数!")
- else:
- if value[0] in self:
- super().remove(value[0])
- print("成功将元素"%s"删除啦~" % value)
- else:
- print("出错啦!传入的元素不存在哦!")
- return
复制代码
|
|