使用`list(dict_keys())`在这里为什么会返回一个空列表?

huangapple go评论66阅读模式
英文:

Why does using list(dict_keys()) here, return an empty list?

问题

我试图创建一个代表图书馆的类其中包括一个嵌套类来代表单本书

当我打印出Library.available_books时我得到了预期的结果
`dict_keys(['Book1', 'Book2'])`

但是当我尝试将dict_keys转换为列表时像这样
`available_books = list(Book.book_data.keys())`

打印Library.available_books给我一个空列表Python为什么会将键转换为空列表呢
英文:

I am trying to make a Class to represent a Library with a nested class to represent the individual books.

class Library:
    class Book:
        book_data = {}
        def __init__(self, title, year, isbn, author):
            self.title = title
            self.year = year
            self.isbn = isbn
            self.author = author
            Library.Book.book_data[title]={'Date Published':year,'ISBN':isbn,'Auhthor':author}
    
    def __init__(self, username):
        self.username = username
        self.borrowed_books = []

    def checkout_book(self, book_name):
        pass

    def return_book(self, book_name):
        pass

    available_books = Book.book_data.keys() 

When I print out Library.available_books I get the expected result:
dict_keys(['Book1','Book2'])

However when I try to convert dict_keys to list by doing so:
available_books = list(Book.book_data.keys())

Printing Library.available_books gives me an empty list. Is there a reason why python is converting the keys into an empty list?

答案1

得分: 4

available_books = Book.book_data.keys() 仅在字典为空时运行一次。其值在每次访问时不会更改。 dict.keys() 返回键的视图,因此在更改底层的dict后,您可以看到修改,但转换为list仅捕获了在初始化available_books时的键(此时没有键)。

英文:

available_books = Book.book_data.keys() is run only once, when the dict is empty. Its value will not change each time it is accessed. dict.keys() returns a view of the keys, so you can see modifications after changing the underlying dict, but converting to a list only captures the keys (of which there are none) at the moment available_books is initialized.

huangapple
  • 本文由 发表于 2023年2月14日 08:22:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442394.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定