通过定义新类访问列表的名称,错误:NamedList实例没有属性'__len__' [英] Accessing the name of a list by defining a new class, error: NamedList instance has no attribute '__len__'

查看:69
本文介绍了通过定义新类访问列表的名称,错误:NamedList实例没有属性'__len__'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python很陌生, 所以我创建了一个像这样的元素列表:

I am pretty new to python, So I have created a list of elements like:

main_list = [1,2,3]

我希望此列表具有名称,并且我不想使用字典,所以我创建了一个以名称为属性的类:

I want this list to have a name and I don't want to use a dictionary, so I have created a class with the name as an attribute:

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

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

when I try to access the length of the first list:

len(main_list)   #works fine

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

but for the second one it gives me this

错误:NamedList实例没有属性' len ':

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

我想知道为什么List类的基本属性对我的类不可用?我所有的实例最初都是一个List实例.

I wanted to know why the basic attributes of the List class are not available for my class? all my instances are originally a List instance.

预先感谢

推荐答案

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

You can create a subclass of list and it will inherit all of the list methods, including .__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__()进行的,但是您的原始类没有该方法.相反,它具有.object.__len__(),换句话说,它具有一个列表对象,而那个具有必需的方法. len(new_main_list)不起作用,但len(new_main_list.object)可以.

Having a list attribute is not the same as being a list. Think about what len() is supposed to do if you have multiple list attributes, or no lists. You weren't exposing the required interface. The len() builtin works by calling .__len__() on the object, but your original class didn't have that method. Instead it has .object.__len__(), in other words, it has a list object and that has the required method. len(new_main_list) doesn't work, but len(new_main_list.object) would have.

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

The subclass, on the other hand, inherits the attributes of its parent class (list). If an attribute lookup on NamedList fails, it will try looking it up on list, which has .__len__(), so it works.

这篇关于通过定义新类访问列表的名称,错误:NamedList实例没有属性'__len__'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆