Accessing the name of a list by defining a new class, error: NamedList instance has no attribute '__len__'

Accessing the name of a list by defining a new class, error: NamedList instance has no attribute '__len__'

我对 python 很陌生, 所以我创建了一个元素列表,例如:

main_list = [1,2,3]

我希望这个列表有一个名称,但我不想使用字典,所以我创建了一个 class 并将名称作为属性:

class NamedList:
     def __init__(self, name, obj)
          self.name = name
          self.object = obj

当我尝试访问第一个列表的长度时:

len(main_list)   #works fine

但是对于第二个,它给了我这个

error: NamedList instance has no attribute 'len' :

new_main_list = NamedList('numbers', main_list)
len(new_main_list)      #This line gives me the error

我想知道为什么列表 class 的基本属性不适用于我的 class?我所有的实例最初都是一个列表实例。

提前致谢

__len__ 方法添加到您的 class 赞中,

def __len__(self):
    return len(self.obj) # or return self.obj.__len__()

您可以创建 list 的子class,它将继承所有列表方法,包括 .__len__().

class NamedList(list):
    def __init__(self, name, iterable):
        super().__init__(iterable)
        self.name = name

all the instances are list instances originally, so why methods of the list class do not work for them and why I have to define a subclass?

具有 列表属性与成为 列表不同。想想如果你有多个列表属性,或者没有列表,len() 应该做什么。您没有公开所需的接口。 len() 内置函数通过在对象上调用 .__len__() 来工作,但是您原来的 class 没有那个方法。相反,它有 .object.__len__(),换句话说,它有一个列表对象,that 有所需的方法。 len(new_main_list) 不起作用,但 len(new_main_list.object) 会起作用。

另一方面,

子class继承其父class(list)的属性。如果 NamedList 上的属性查找失败,它将尝试在具有 .__len__()list 上查找它,因此可以正常工作。