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

守給你的承諾、 提交于 2021-02-11 14:44:12

问题


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

error: NamedList instance has no attribute 'len' :

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

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.

Thanks in advance


回答1:


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?

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.

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.




回答2:


Add __len__ method to your class like,

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


来源:https://stackoverflow.com/questions/60427254/accessing-the-name-of-a-list-by-defining-a-new-class-error-namedlist-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!