You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python预定义整数键字典遍历与property封装问题如何解决?

报错原因
  • 遍历字典未调用items()方法:Python直接遍历字典时默认仅迭代键(也就是你这里的1001、1002等整数),你尝试对单个int值拆包为key,value两个变量,就会触发对应报错,和键是整数类型没有关系,你的字典结构本身没有问题。
  • 循环内提前return:当前写法在第一次循环时就会返回结果,只会拿到第一条数据,无法输出所有条目。
实现方案

你想用property封装私有字典、返回副本避免外部修改原数据的思路是正确的,符合封装要求,也方便后续做内部增删改操作的管控。
完整实现代码如下:

import copy

class BookManager:
    def __init__(self):
        self.__books = {
            1001: {'title': 'Introduction to Programming', 'author': 'Farell', 'copies': 2}, 
            1002: {'title': 'Database Concepts', 'author': 'Morris', 'copies': 5}, 
            1003: {'title': 'Object Oriented Analysis', 'author': 'Farell', 'copies': 4}, 
            1004: {'title': 'Linux Operating System', 'author': 'Palmer', 'copies': 2}, 
            1005: {'title': 'Data Science using Python', 'author': 'Russell', 'copies': 4}, 
            1006: {'title': 'Functional Programming with Python', 'author': 'Babcock', 'copies': 6}
        }
    
    @property
    def books(self):
        # 返回深拷贝,彻底避免外部修改原私有字典数据
        return copy.deepcopy(self.__books)
    
    def get_formatted_books(self):
        lines = []
        # 调用items()获取键值对再遍历
        for book_id, book_info in self.__books.items():
            line = f"  {book_id} : title: {book_info['title']}, author: {book_info['author']}, copies: {book_info['copies']}"
            lines.append(line)
        return '\n'.join(lines)
使用示例
# 实例化类
manager = BookManager()
# 打印格式化输出
print(manager.get_formatted_books())
# 获取books字典副本做操作,不会影响内部私有数据
books_copy = manager.books
books_copy[1001]['copies'] = 10
print(manager.books[1001]['copies']) # 输出还是2,原数据未被修改

内容的提问来源于stack exchange,提问作者Darosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 01:54:06