【发布时间】:2021-11-25 17:49:09
【问题描述】:
我正在创建一个自定义类 mylist,它继承自 python 中的 list。
但我无法附加值
class mylist(list):
def __init__(self,max_length):
super().__init__()
self.max_length = max_length
def append(self, *args, **kwargs):
""" Append object to the end of the list. """
if len(self) > self.max_length:
raise Exception
a = mylist(5)
a.append(5)
print(a)
# output
#[]
【问题讨论】:
-
你的问题是什么?
-
我需要在 python 中继承内置的 'list' 数据类型并创建一个具有 max_length 属性的自定义列表
-
你需要编写实现;设置练习的目的是让你思考和学习,而不是复制。你如何从现有的类继承?覆盖继承的方法?列表中的哪些方法会改变长度?
-
是的。我已经尝试过我自己的类 mylist(list): def __init__(self): super().__init__() self.max_length = 0 def append(self, *args, **kwargs): """ 将对象附加到列表末尾。“”” if len() > self.max_length: raise Exception 我在这之后感到震惊
-
什么是“被击中” - 你的实现有什么具体问题?给minimal reproducible example。
标签: python python-3.x list inheritance