英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论