Reputation: 37
I am trying to make a class that includes the ability to display the length of a list. However, I get the message 'List has 0 items' instead of the actual number.
Here is my code:
'''
grocery_list = []
class GroceryList:
grocery_list = []
def __init__(self):
print('Grocery List Created')
def add(self, item):
self.grocery_list.append(item)
def show(self):
print(self.grocery_list)
def size(self):
print('List has {} items'.format(len(grocery_list)))
gro_list = GroceryList()
gro_list.add('Banana')
gro_list.add('Cat Food')
gro_list.show()
gro_list.size()
'''
Any help is appreciated.
Upvotes: 1
Views: 262
Reputation: 4779
grocery_list
in your code. One is a global one and the other is a class variable.len(grocery_list)
You are finding the length of the grocery_list
that is declared before the Class (global). Since you're not adding to that list (see your add()
function), it shows you 0
items.len(self.grocery_list)
- means find the length of grocery_list
(class variable). See the self
before the variable name.class GroceryList:
grocery_list = []
def __init__(self):
print('Grocery List Created')
def add(self, item):
self.grocery_list.append(item)
def show(self):
print(self.grocery_list)
def size(self):
print('List has {} items'.format(len(self.grocery_list)))
gro_list = GroceryList()
gro_list.add('Banana')
gro_list.add('Cat Food')
gro_list.show()
gro_list.size()
Grocery List Created
['Banana', 'Cat Food']
List has 2 items
Upvotes: 1
Reputation: 2244
In your question the indentation was messed up, however the problem was in method size(self)
with grocery_list
used instead of self.grocery_list
.
Everything else works OK.
class GroceryList:
# declare grocery_list
grocery_list = []
def __init__(self):
print('Grocery List Created')
def add(self, item):
self.grocery_list.append(item)
def show(self):
print(self.grocery_list)
def size(self):
# self.grocery_list was the error
print('List has {} items'.format(len(self.grocery_list)))
if __name__ == "__main__":
gro_list = GroceryList()
gro_list.add('Banana')
gro_list.add('Cat Food')
gro_list.show()
gro_list.size()
Upvotes: 1
Reputation: 3011
The reason you get zero in your code is that you are appending to the list (grocery_list) which is an attribute of the class. But in the size()
function you are printing the length of the global grocery_list
in which no elements were appended (i.e it is an empty list) so you get length as '0'
Try changing your size()
function to this -
def size(self):
print('List has {} items'.format(len(self.grocery_list)))
Also, you can remove the grocery_list
variable at the global level (first line), because it is useless in this code.
Upvotes: 0