Python - 类中的字典无法按预期运行

时间:2016-08-31 15:01:44

标签: python dictionary

我有一个非常基本的类Library,我用传入的字典(键簿名称(字符串),值簿架位置(int))初始化它,并且已经输入了值。代码如下所示:

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")

由于某种原因,我无法从get_location方法访问字典中的数据,但我能够在initialize方法中访问字典数据(我之前测试过代表方法,它也在那里工作)。这是我得到的错误:

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

我希望它打印出Book1的位置,这是一个2。

2 个答案:

答案 0 :(得分:1)

您正在创建一个将现有实例传递到的 Library实例:

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

这会为您提供Library()个实例,其中book_table 另一个 Library()实例,而不是字典!

您想在get_location()上直接致电libraries[0]

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

你也可以在列表中存储 book_table词典:

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

但只有在出于某种原因无法直接在列表中存储Library实例时才需要这样做。

答案 1 :(得分:0)

Library(libraries[0])您再次致电 init

此代码应该有效

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")