itman1234
itman1234

Reputation: 57

Python - Dictionary in class not functioning as expected

I have a very basic class Library, and I initialize it with a passed in dictionary (key book name (string), value book shelf location (int)) with values already entered into it. The code looks like this:

class Library(object):
    def __init__(self, book_table):
        self.book_table = book_table

    def get_location(self, book_name):
        if book_name in self.book_table: # ERROR RIGHT HERE
            return self.book_table[book_name]
        else:
            return "Book Not Found"

libraries = []
libraries.append(Library({"Book1":2, "Book2":9}))
print Library(libraries[0]).get_location("Book1")

For some reason, I am unable to access data from the dictionary from the get_location method, but I am able to access the dictionary data in the initialize method (and I previously tested the represent method and it worked in there too). This is the error I get:

Traceback (most recent call last):
  File "C:/Users/Owner/Documents/Programming/PyCharm/Book_Locator/Book_Locator.py", line 13, in <module>
    print Library(libraries[0]).get_location("Book1")
  File "C:/Users/Owner/Documents/Programming/PyCharm/Book_Locator/Book_Locator.py", line 6, in get_location
    book_name in self.book_table:
TypeError: argument of type 'Library' is not iterable

I expected it to print out Book1's location, which is a 2.

Upvotes: 1

Views: 446

Answers (2)

giaosudau
giaosudau

Reputation: 2251

Library(libraries[0]) you call init again

This code should works

class Library(object):
    def __init__(self, book_table):
        self.book_table = book_table

    def get_location(self, book_name):
        if book_name in self.book_table:  # ERROR RIGHT HERE
            return self.book_table[book_name]
        else:
            return "Book Not Found"


libraries = []
libraries.append(Library({"Book1": 2, "Book2": 9}))

print libraries[0].get_location("Book1")

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1125068

You are creating a new Library instance that you pass your existing instance into:

print Library(libraries[0]).get_location("Book1")
#     ^^^^^^^ ^^^^^^^^^^^^
#        |        \----------- an existing instance of Library
#  A new instance of Library

This gives you a Library() instance where book_table is another Library() instance, not a dictionary!

You'd want to call get_location() directly on libraries[0]:

print libraries[0].get_location("Book1")

You could also just store just the book_table dictionary in the list:

libraries = [{"Book1": 2, "Book2": 9}]
print Library(libraries[0]).get_location("Book1")

but this would only be needed if you could not store Library instances in the list directly for whatever reason.

Upvotes: 1

Related Questions