【问题标题】:Cannot append value to list in Python?无法将值附加到 Python 中的列表?
【发布时间】: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


【解决方案1】:

您定义了自己的append(),因此您替换了原来的append(),它不会将元素添加到列表中。

您可以使用super() 运行原始的append()

    def append(self, *args, **kwargs):
        """ Append object to the end of the list. """
        if len(self) > self.max_length:
            raise Exception

        if args:
            super().append(args[0])

我认为您应该使用>= 而不是>,因为您在添加项目之前会检查它。如果您在添加项目后检查它,您可以使用>


顺便说一句:

因为您使用*args,所以您可以使用for-loop 来附加可能值a.append(5, 6, 7)。原append()不能这样做。

        for item in args:        
            super().append(item)

可能需要检查len(self) + len(args) > self.max_length 是否是len(self)for-loop 中

您还可以检查args 是否有任何值,并在运行a.append() 没有任何值时引发错误。


class MyList(list):  # PEP8: `CamelCaseNames` for classes

    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
        
        #if args:
        #    super().append(args[0])

        if not args: # use `TypeError` like in `list.append()`
            raise TypeError("descriptor 'append' of 'list' object needs an argument")

        for item in args:
            if len(self) >= self.max_length:
                 raise Exception
            super().append(item)

    def insert(self, pos, value):
        if len(self) >= self.max_length:
            raise Exception
        super().insert(pos, value)

# --- main ---

#list.append()  # raise `TypeError`
            
a = MyList(5)

try:
    a.append()  # raise `TypeError` like in `list.append()`
except Exception as ex:
    print('ex:', ex)

a.append(5)
print(a)      # [5]

a.append(6, 7, 8, 9)
print(a)      # [5, 6, 7, 8, 9]

a.append(10)  # raise ERROR

a.insert(0, 999)  # raise ERROR

PEP 8 -- Style Guide for Python Code

【讨论】:

  • 谢谢,这真的很有帮助。我已经覆盖了用于附加多个值的扩展方法
  • 我在完整示例中添加了一些修改。
  • 顺便说一句:如果你想附加许多元素,那么你可以使用标准的a.extend( [5,6,7] )或更短的a += [5,6,7]——这样你就不必定义自己的类了。
  • 是的,但我需要检查我是否超过了 max_length。如果用户尝试使用多个项目扩展列表,那么只有其中一些适合?例如,如果 max_length 为 5,当前长度为 4,并且用户尝试扩展 5 个元素,则只有一个应该填充
  • 在新版本中,我在for-loop 中检查len(self),因此它会引发错误,但它会添加适合max_length 的值。如果您执行a.append(1,2,3,4,5,6)(并且您发现错误),那么您会得到[1,2,3,4,5] 而没有6。你也应该写自己的extend()insert()来检查max_length
【解决方案2】:

你是说这个吗?

class mylist(list):

    def __init__(self,lists:list,max_length:int):
        super().__init__()
        self.lists = lists
        self.max_length = max_length
    def get_list(self):
        return self.lists
    def append(self, *args, **kwargs):
        if len(self.lists) > self.max_length:
            raise Exception
        else:
            self.lists.append(*args)

a = mylist([5,4,3,2])
a.append(54)
print(a.lists)
#OR
print(a.get_list())

【讨论】:

  • @Tomerikoo 其实告诉我你需要什么?因为你想追加到一个列表吗?
  • @Tomerikoo 好的好的谢谢
猜你喜欢
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-28
  • 2019-03-29
  • 2023-02-02
  • 2021-12-01
  • 2019-03-29
相关资源
最近更新 更多